Oops4
Oops4
Collection in Java
→ In Java, Collection refers to a framework provided by 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.
→ 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.
Page 1
Iterator Interface
1. Traversal: It allows sequential access to the elements of a collection. This enables iterating over the
elements of a collection without needing to know its internal structure.
2. Uniformity: Iterator provides a common way to iterate over different types of collections. This
uniformity simplifies the process of iterating through collections.
3. Safe removal: Iterator supports safe removal of elements from a collection during iteration.
4. Enhanced for loop Support: The Iterator interface is utilized implicitly in the enhanced 'for' loop syntax.
This syntax provides a concise and readable way to iterate over collections without explicitly dealing
with iterators.
Collection Interfaces
→ 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 [Link].
→ 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.
List Interface
1. Ordered Collections
2. Indexed Access
3. Dynamic Size
4. Iterable
5. Search Operations
Page 2
Array List
→ The ArrayList class is a resizable array, which can be found in the [Link] package. The difference
between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (if you
want to add or remove elements to/from an array, you have to create a new one).
Linked List
→ The LinkedList class is a collection which can contain many objects of the same type, just like the
ArrayList.
→ The LinkedList class has all of the same methods as the ArrayList class because they both implement
the List interface. This means that you can add items, change items, remove items and clear the list in
the same way.
→ However, while the ArrayList class and the Linked List class can be used in the same way, they are
built very differently.
import [Link].*;
public class TestJavaCollection2{ Output:
public static void main(String args[]){ Ravi
LinkedList<String> al-new LinkedList<String>(); Vijay
[Link]("Ravi"); Ravi
[Link]("Vijay"); Ajay
[Link]("Ravi");
[Link]("Ajay");
Iterator<String> itr=[Link]():
while([Link]()){
[Link]([Link]());
}
}
}
Page 3
Vector
→ They are very similar to ArrayList, but Vector is synchronized and has some legacy methods that the
collection framework does not contain.
→ It also maintains an insertion order like an ArrayList. Still, it is rarely used in a non-thread
environment as it is synchronized, and due to this, it gives a poor performance in adding, searching,
deleting, and updating its elements.
→ The Iterators returned by the Vector class are fail-fast. In the case of concurrent modification, it fails
and throws the ConcurrentModificationException.
→ 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.
Stack
→ Java Collection framework provides a Stack class that models and implements a Stack data structure.
→ The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop
operations, the class provides three more functions of empty, search, and peek.
→ The class can also be said to extend Vector and treats the class as a stack with the five mentioned
functions. The class can also be referred to as the subclass of Vector.
→ 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.
Page 4
Queue Interface
→ The Queue interface is present in [Link] package and extends the Collection interface is used to hold
the elements about to be processed in FIFO(First In First Out) order.
→ It is an ordered list of objects with its use limited to inserting elements at the end of the list and deleting
elements from the start of the list, (i.e.), it follows the FIFO or the First-In-First-Out principle.
→ 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
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.
→ Array Deque is faster than ArrayList and Stack and has no capacity restrictions.
Page 5
Set Interface
→ The set interface is present in [Link] 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 Navigable Set.
→ The set interface is present in [Link] 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 Navigable Set.
Hash Set
→ 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.
Declaration of HashSet
public class HashSet<E> extends AbstractSet<E> implements Set<E>, cloneable, Serializable
where E is the type of elements stored in a HashSet
Page 6
LinkedHashSet
→ 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.
→ HashSet, It also contains unique elements. It maintains the insertion order and permits null elements.
→ The SortedSet interface present in [Link] 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.
Key Characteristics :-
Page 7
Tree Set
→ 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.
Key Characteristics :-
1. Sorted order
2. Unique elements
3. Efficient operations
4. Iterating in sorted order
5. Use of Red-Black tree
Map Interface
1. The Map interface in Java represents a collection of key-value pairs, where each key is associated with
a corresponding value.
2. It provides a way to store and retrieve elements based on their keys.
3. Keys are unique within a map, meaning that each key can map to at most one value
4. The Map interface provides an efficient retrieval and manipulation of values based on their keys.
5. This makes maps suitable for scenarios where quick access to values based on unique identifiers is
required.
Key Characteristics :-
1. Key - Value Pairs - Map stores Elements as key-value pairs, where each key is associated with a
corresponding value
2. Uniqueness of Keys :- Each Key in a map is unique.
3. No Ordering :- Maps do not maintain any inherent ordering of their Elements.
4. Effiecient Retrieval :- Maps provide effiecient method for retrieval values based on their corresponding
keys.
1. Associative data structure: Maps provide an associative data structure that allows elements to be stored
and retrieved based on unique keys.
2. Flexible storage: Maps offer flexibility in storing and organizing data.
3. Key uniqueness: Maps enforce the uniqueness of keys within the collection.
4. Integration with Collections framework: The Map interface integrates seamlessly with other interfaces
and classes in the Java Collections framework.
5. Multiple implementations: The Map interface allows multiple implementations with different
performance characteristics and usage patterns
Page 8
Java HashMap
→ HashMap in Java is like the legacy Hashtable class, but it is not synchronized.
→ It allows us to store the null elements as well, but there should be only one null key.
→ Since Java 5, it is denoted as HashMap<K,V>, where K stands for key and V for value. It inherits the
AbstractMap class and implements the Map interface.
Example2
Page 9
Linked Hash Map
→ 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.
Declaration:
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>
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 the values mapped in the map
It implements Map<K,V> interface, and extends HashMap<K,V> class.
→ A LinkedHashMap is an extension of the HashMap class and it implements the Map interface.
Therefore, the class is declared as:
public class LinkedHashMap<K,V>
extends HashMap<K,V>
implements Map<K,V>
→ 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:
Hash: All the input keys are converted into a hash which is a shorter form of the key so that the search and
insertion are faster.
Key: Since this class extends HashMap, the data is stored in the form of a key-value pair. Therefore, this
parameter is the key to the data.
Value: For every key, there is a value associated with it. This parameter stores the value of the keys. Due to
generics, this value can be of any form.
Next: Since the LinkedHashMap stores the insertion order, this contains the address to the next node of the
LinkedHashMap.
Previous: This parameter contains the address to the previous node of the LinkedHashMap.
Hash Table
→ 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 [Link] 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.
Page 10
→ 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.
Features of Hashtable:
TreeMap Class
Page 11
Sorting in Java
→ 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 and there are two in-
built methods to sort in Java.
→ Java Comparable interface is used to order/sort the objects of the user-defined class.
→ This interface is found in [Link] 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.
Page 12
We can sort the elements of:
○ String objects
○ Wrapper class objects
○ User-defined class objects
Collections class
→ 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.
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.
Comparator Interface
Page 13
Properties Class
→ The Properties class represents a persistent set of properties. The Properties can be saved to a
stream or loaded from a stream.
→ It belongs to [Link] package. Properties define the following instance variable. This variable holds
a default property list associated with a Properties object.
Properties defaults: This variable holds a default property list associated with a Properties object.
Note: The Properties class does not inherit the concept of a load factor from its superclass, Hashtable.
Declaration
Constructors of Properties
2. Properties(Properties propDefault): The second creates an object that uses propDefault for its default
value.
Properties p = new Properties(Properties propDefault);
Page 14
Differences
Page 15