Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

OOPS With Java Unit 4

Uploaded by

poojaandipad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

OOPS With Java Unit 4

Uploaded by

poojaandipad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Object Oriented Programming with Java

AKTU
Unit :- 4 BCS-403
Java Collections Framework

The Collection in Java is a framework that provides an architecture to


store and manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.
In Java, "Collections" refers to a framework provided in the Java API to
manage and manipulate groups of objects. These objects are commonly
referred to as elements or items.
The Collections framework provides a unified architecture for working with
collections of objects. It allows developers to easily store, retrieve,
manipulate, and iterate over these collections.
Key features of Collections:
The Java Collections framework is a set of classes and interfaces that provide
implementations of commonly reusable collection data structures in Java.

The data structures can be lists, sets, maps, queues, etc.

It provides a unified architecture for manipulating and storing groups of objects.


Advantages of Java Collection Framework :-
1. The Utility Package (java.util)
contains all the classes &
interfaces that are required by
the collection framework.

2. The collection framework


contains an interface named an
iterable interface which
provides the iterator to iterate
through all the collections.
This interface is extended by
the main collection interface
which acts as a root for the
collection framework.

3. All the collections extend this


collection interface thereby
extending the properties of the
iterator and the methods of this
interface.
The Collection interface is the root interface in the Java Collections
framework hierarchy. It represents a group of objects, known as elements,
and provides a unified way to work with collections of objects in Java.

The Collection interface defines a set of operations that can be performed


on collections, regardless of their specific implementation. The Collection
interface does not specify any particular ordering of elements.

The Collection interface allows duplicate elements.

Overall, the Collection interface serves as a fundamental building block for


working with collections of objects in Java. It provides a common set of
operations and behaviours that can be used across different types of
collections.
Collection is called interface in java whereas Collections is called a
utility class in java and both of them can be found in java. util.
package. Collection is used to represent a single unit with a group of
individual objects whereas collections is used to operate on collection
with several utility methods.
This is a child interface of the collection interface.
This interface is dedicated to the data of the list type in which we can
store all the ordered collections of the objects.
This also allows duplicate data to be present in it. This list interface is
implemented by various classes like ArrayList, Vector, Stack, etc.
Since all the subclasses implement the list, we can instantiate a list
object with any of these classes.

1. Ordered Collections 4. Iterable

2. Indexed Access 5. Search Operations

3. Dynamic Size
The LinkedList stores its items in "containers." The list has a link to the first container
and each container has a link to the next container in the list. To add an element to the
list, the element is placed into a new container and that container is linked to one of the
other containers in the list.
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is
synchronized and contains many methods that are not part of Collection framework.
It implements the last-in-first-out data structure, i.e., Stack. The stack contains all of the methods of
Vector class and also provides its methods like boolean push(), boolean peek(), boolean
push(object o), which defines its properties.
Being an interface the queue needs a concrete
class for the declaration and the most common
classes are the PriorityQueue and LinkedList in
Java. Note that neither of these implementations
is thread-safe. PriorityBlockingQueue is one
alternative implementation if the thread-safe
implementation is needed
Queue interface maintains the first-in-first-out order.
It can be defined as an ordered list that is used to hold the elements which
are about to be processed.
There are various classes like PriorityQueue, Deque, and ArrayDeque
which implements the Queue interface.

Queue interface can be instantiated as:

1. Queue<String> q1 = new PriorityQueue();

2. Queue<String> q2 = new ArrayDeque();

There are various classes that implement the Queue interface,


some of them are given below.
The Deque (double-ended queue) interface in Java is a subinterface of the
Queue interface and extends it to provide a double-ended queue, which is a
queue that allows elements to be added and removed from both ends. The
Deque interface is part of the Java Collections Framework and is used to
provide a generic and flexible data structure that can be used to implement a
variety of algorithms and data structures.

Deque interface extends the Queue interface. In Deque, we can remove and add
the elements from both the side. Deque stands for a double-ended queue which
enables us to perform the operations at both the ends.

Deque can be instantiated as:


Deque d = new ArrayDeque();
The ArrayDeque class in Java is an implementation of the Deque interface that uses a resizable array to store its
elements. This class provides a more efficient alternative to the traditional Stack class, which was previously
used for double-ended operations. The ArrayDeque class provides constant-time performance for inserting and
removing elements from both ends of the queue, making it a good choice for scenarios where you need to
perform many add and remove operations.
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue, we can
add or delete the elements from both the ends.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
The set interface is present in java.util package and extends the Collection interface. It is an unordered
collection of objects in which duplicate values cannot be stored. It is an interface that implements the
mathematical set. This interface contains the methods inherited from the Collection interface and adds
a feature that restricts the insertion of the duplicate elements. There are two
interfaces that extend the set implementation namely SortedSet and NavigableSet.
In the above image, the navigable set extends the sorted set interface. Since a
set doesn’t retain the insertion order, the navigable set interface provides the
implementation to navigate through the Set. The class which implements the
navigable set is a TreeSet which is an implementation of a self-balancing tree.
Therefore, this interface provides us with a way to navigate through this tree.
Set Interface in Java is present in java.util package. It extends the Collection interface.
It represents the unordered set of elements which doesn't allow us to store the
duplicate items. We can store at most one null value in Set. Set is implemented by
HashSet, LinkedHashSet, and TreeSet. Set can be instantiated as:
Java HashSet class implements the Set interface, backed by a hash table which is actually
a HashMap instance. No guarantee is made as to the iteration order of the hash sets which means
that the class does not guarantee the constant order of elements over time. This class permits the
null element. The class also offers constant time performance for the basic operations like add,
remove, contains, and size assuming the hash function disperses the elements properly among the
buckets, which we shall see further.

where E is the type of elements stored in a HashSet


The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all
elements. When the iteration order is needed to be maintained this class is used. When iterating
through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the
elements in the order in which they were inserted. When cycling through LinkedHashSet using an
iterator, the elements will be returned in the order in which they were inserted.
LinkedHashSet class represents the LinkedList implementation of Set
Interface. It extends the HashSet class and implements Set interface.
Like HashSet, It also contains unique elements. It maintains the insertion
order and permits null elements.
The SortedSet interface present in java.util package extends the Set interface present in
the collection framework. It is an interface that implements the mathematical set. This interface
contains the methods inherited from the Set interface and adds a feature that stores all the
elements in this interface to be stored in a sorted manner.
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses
a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering
whether or not an explicit comparator is provided. This must be consistent with equals if it is to
correctly implement the Set interface.

Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet also
contains unique elements. However, the access and retrieval time of TreeSet is quite fast. The elements in
TreeSet stored in ascending order.

1. Sorted order 4. Iterating in sorted order

2. Unique elements 5. Use of Red-Black tree

3. Efficient operations
Map stores Elements as
key-value pairs, where
each key is associated with a correspending value.
2. Uniqueness of Keys :- Each Key in a map is unique.
The LinkedHashMap Class is just like HashMap with an additional feature of maintaining an order of
elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it
never maintained the track and order of insertion, which the LinkedHashMap provides where the elements
can be accessed in their insertion order.
Important Features of a LinkedHashMap are listed as
follows:

Here, K is the key Object type and V is the value Object type
K – The type of the keys in the map.
V – The type of values mapped in the map.
It implements Map<K, V> interface, and extends HashMap<K, V> class.
Though the Hierarchy of LinkedHashMap is as depicted as follows:
A LinkedHashMap is an extension of the HashMap class and it implements
the Map interface.Therefore, the class is declared as:
In this class, the data is stored in the form of nodes. The implementation
of the LinkedHashMap is very similar to a doubly-linked list. Therefore,
each node of the LinkedHashMap is represented as:
The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a
key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must
implement the hashCode method and the equals method.

The java.util.Hashtable class is a class in Java that provides a key-value data structure, similar to the Map
interface. It was part of the original Java Collections framework and was introduced in Java 1.0.

However, the Hashtable class has since been considered obsolete and its use is generally discouraged. This is
because it was designed prior to the introduction of the Collections framework and does not implement the
Map interface, which makes it difficult to use in conjunction with other parts of the framework. In addition, the
Hashtable class is synchronized, which can result in slower performance compared to other implementations
of the Map interface.

In general, it’s recommended to use the Map interface or one of its implementations (such as HashMap or
ConcurrentHashMap) instead of the Hashtable class.
It is similar to HashMap, but is synchronized.
Hashtable stores key/value pair in hash table.
In Hashtable we specify an object that is used as a key, and the value
we want to associate to that key.The key is then hashed, and the
resulting hash code is used as the index at which the value is
stored within the table.
HashMap doesn’t provide any Enumeration, while Hashtable provides not
fail-fast Enumeration.
Whenever we do hear sorting algorithms come into play such as selection sort,
bubble sort, insertion sort, radix sort, bucket sort, etc but if we look closer here we
are not asked to use any kind of algorithms.

It is as simple sorting with the help of linear and non-linear


data structures present within java.
So there is sorting done with the help of brute force in java with the help of loops

Ways of sorting in Java

1. Using loops
2. Using sort() method of Arrays class
3. Using sort method of Collections class
4. Sorting on a subarray
Java Comparable interface is used to order the objects of the user-defined class.
This interface is found in java.lang package and contains only one method named
compareTo(Object). It provides a single sorting sequence only, i.e., you can sort
the elements on the basis of single data member only. For example, it may be
rollno, name, age or anything else.
Collections class provides static methods for sorting the elements of collections.
If collection elements are of Set or Map, we can use TreeSet or TreeMap.
However, we cannot sort the elements of List. Collections class provides methods
for sorting the elements of List type elements.

public void sort(List list): It is used to sort the elements of List.


List elements must be of the Comparable type.

Note: String class and Wrapper classes implement the Comparable


interface by default. So if you store the objects of string or wrapper
classes in a list, set or map, it will be Comparable by default.
A comparator interface is used to order the objects of user-defined classes. A comparator object is
capable of comparing two objects of the same class. Following function compare obj1 with obj2.
Syntax:
public int compare(Object obj1, Object obj2):
Suppose we have an Array/ArrayList of our own class type, containing fields like roll no, name,
address, DOB, etc, and we need to sort the array based on Roll no or name?

Method 1: One obvious approach is to write our own sort() function using one of the standard
algorithms. This solution requires rewriting the whole sorting code for different criteria like Roll No.
and Name.

Method 2: Using comparator interface- Comparator interface is used to order the objects of a
user-defined class. This interface is present in java.util package and contains 2 methods
compare(Object obj1, Object obj2) and equals(Object element).
Using a comparator, we can sort the elements based on data members. For instance, it may be on
roll no, name, age, or anything else.
Method of Collections class for sorting List elements is used to sort the
elements of List by the given comparator.

public void sort(List list, ComparatorClass c)

To sort a given List, ComparatorClass must implement a Comparator


interface.
How do the sort() method of Collections class work?
Internally the Sort method does call Compare method of the classes it is
sorting. To compare two elements, it asks “Which is greater?”

Compare method returns -1, 0, or 1 to say if it is less than, equal, or


greater to the other. It uses this result to then determine if they should be
swapped for their sort.
Advantage of a Properties file

In the event that any data is changed from the properties record, you don’t have to recompile the
java class. It is utilized to store data that is to be changed habitually.

Note: The Properties class does not inherit the concept of a load factor from its superclass,

Hashtable Declaration
public class Properties extends Hashtable<Object,Object>

Constructors of Properties

1. Properties(): This creates a Properties object that has no default values.


Properties p = new Properties();

2. Properties(Properties propDefault): The second creates an object that uses propDefault


for its default value.
Properties p = new Properties(Properties propDefault);

You might also like