Java Collection FrameWorks

The Java Collection Framework is a built-in library in Java that provides a set of interfaces, implementations, and algorithms for managing collections of objects. It is designed to be efficient, easy to use, and flexible. The below-given diagram demonstrates the hierarchy of the collection framework. The Collection interface is implemented by all the classes in the collection framework. List, Queue, and Set are the child interfaces of the collection interface.

Collection framework

Iterable Interface

The Iterable interface is the core interface for all the collection classes. The Collection interface extends the Iterable interface; therefore, all the subclasses of the Collection interface also implement the Iterable interface. The interface provides a single abstract method.

Iterator<T> iterator()

It returns an iterator over the elements in the collection.

Collection Interface

The Collection interface is the core interface of the collection framework. All the classes in the collection framework implement the collection interface. It is used to represent a group of objects (elements) as a single unit. It declares the methods that every collection will have.

Some of the methods in the Collection interface are,

  • add(E e): Adds the specified element to the collection.
  • remove(Object o): Removes a specific element from the collection.
  • size(): Provides the number of elements in the collection.
  • isEmpty(): Checks whether the collection is empty.
  • contains(Object o): Checks whether the collection contains the specified element.
  • clear(): Removes all elements from the collection.
  • toArray(): Returns an array of all elements in the collection.
  • iterator(): Returns an iterator through the elements of the collection.

List Interface

List is an ordered collection of elements. The elements are accessed based on their index position in the list. It may contain duplicates.

Some of the important methods in the List interface are,

  • add(int index, E element): Inserts a specific element at a specific position in the list.
  • get(int index): Get the element at the specific index in the list.
  • set(int index, E element): Set the element at the particular position in the list with the specified element.
  • remove(int index): Remove the element at the selected index.
  • indexOf(Object o): Returns the index of the first occurrence of the given element in the list. It returns -1 if the list does not contain the element.
  • lastIndexOf(Object o): Returns the index of the last occurrence of the given element in the list. It returns -1 if the list does not contain the element.
  • subList(int fromIndex, int toIndex): Returns a view of the portion of the list between the specified fromIndex, inclusive, and toIndex, exclusive.

The list interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

ArrayList

List <Type> arrayList = new ArrayList(); 

ArrayList implements the list interface. ArrayList uses the dynamic array to store the elements. The ArrayList stores the elements in the insertion order, and it is not synchronized. The elements can be accessed from ArrayList based on their index position in the list.

The size of an ArrayList is increased automatically if the collection grows or shrinks if the objects are removed from the collection. When we add more elements to an ArrayList, and it exceeds the size of the array list, a new ArrayList will be created, and all the values will be put on the new ArrayList.

LinkedList

List <Type> linkedList = new LinkedList ();

LinkedList is also an implementation of the List interface. LinkedList uses a doubly linked list to store elements. In a doubly LinkedList, each node contains data and reference to the previous and next nodes. Insertion and deletion are easy in LinkedList. Because when a new element is added to a LinkedList, a node will be created and linked to the nearby nodes.

Vector

List <Type> vector = new Vector();

Like the ArrayList, Vector uses a dynamic array to store the data elements. But, Vector is synchronized and contains many methods that are not part of the Collection framework. The Vector class is thread-safe, meaning multiple threads can safely access and modify the same instance of the Vector. However, the synchronized methods can impact performance, especially in multi-threaded environments.

Stack

List <Type> stack= new Stack(); 

The Stack is a subclass of the Vector and provides methods for pushing and popping elements from the stack. The stack contains all of the methods of the Vector class along with methods like boolean push(), boolean peek(), boolean push(object o), which defines its properties.

  • push(E item): Adds the specified item to the top of stack.
  • pop(): Remove the item at the top of the stack.
  • peek(): Returns the item at the top of the stack without removing it.
  • empty(): Check whether the stack is empty.
  • search(Object o): Searches the stack for the specified object and returns its position relative to the top of the stack.

Queue Interface

Queue interface follows the first-in-first-out approach. This interface is dedicated to storing the elements where the order of the elements is essential.

Some of the methods in the queue interface are

  • offer(E e): Insert the given element into the queue if it is possible to insert it immediately without violating the capacity restrictions.
  • poll(): Retrieves and removes the head of the queue. It returns null if the queue is empty.
  • peek(): It returns the object at the beginning of the current queue without removing the object from the queue. This method returns null if the queue is empty.
  • element(): Retrieves the head of the queue. If the queue is empty, it throws an exception NoSuchElementException.

PriorityQueue, Deque, and ArrayDeque, implement the Queue interface.

PriorityQueue

Queue<Type> priorityQueue = new PriorityQueue();

PriorityQueue is an implementation of the Queue interface. It contains the elements which are to be processed by their priorities. The elements of the PriorityQueue are ordered based on their natural order or by a Comparator provided at the queue construction time. The head of the PriorityQueue is the least element with respect to the specific ordering. PriorityQueue doesn't allow null values in it.

Deque Interface

The Deque interface extends the Queue interface. Deque means a double-ended queue that enables us to perform the operations at both ends of the Que. In Deque, we can remove and add the elements from both sides.

ArrayDeque

Deque arrayDeque = new ArrayDeque(); 

The ArrayDeque class implements the Deque interface. It is a double-ended queue that allows operations at both ends. It is implemented as a resizable array and provides constant time for insertion and removal operations at both ends of the queue. ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.

Set Interface

Set contains the collection that does not include the duplicate elements. It represents the unordered collection of elements that don't allow duplicate elements. It is very useful to remove the duplicate elements from a list.

Some of the important methods in the set interface are

  • add(E e): Add the element 'e' to the set if it is not already present.
  • remove(Object o): Remove the element 'o' from the set if it is present.
  • contains(Object o): Check whether the specified element is present in the set.
  • isEmpty(): Check whether the set contains any elements.
  • size(): Get the number of elements.
  • clear(): Removes all elements from the set.
  • addAll(Collection<? extends E> c): Adds all elements from the specified collection to the set if they are not already present.
  • retainAll(Collection<?> c): Retains only the elements in the set that are also in the specified collection.
  • removeAll(Collection<?> c): Removes all elements from the set that are also in the specified collection.
  • iterator(): Returns an iterator through the elements in the set.

Implementations of the Set interface are HashSet, LinkedHashSet, and TreeSet.

HashSet

Set<Type> hashSet= new HashSet<Type>();

HashSet is a collection class in the Java Collections Framework that implements the Set interface. HashSet uses a hash table to store the elements and provides constant-time performance for basic operations like add, remove, and contains. It does not maintain the order of elements. It uses the hash code of an element to determine its storage location in the hash table.

LinkedHashSet

Set<Type> linkedHashSet= new LinkedHashSet<Type>();

LinkedHashSet is a Hashtable and LinkedList implementation of a set interface. It contains all unique elements like a HashSet. It stores elements in the insertion order.

LinkedHashSet is a good choice when you need to maintain the insertion order of elements while also ensuring that the elements are unique. However, it may perform slower than HashSet when inserting or removing large numbers of elements due to the overhead of maintaining the linked list.

SortedSet Interface

SortedSet is the alternative to the Set interface, providing total ordering of its elements. The elements of the SortedSet are arranged in the natural ascending order. The SortedSet provides additional methods that inhibit the natural ordering of the elements.

TreeSet

SortedSet<Type> treeSet= new TreeSet();

TreeSet class implements the SortedSet interface that uses a tree for storage. Objects are stored in ascending order. It contains only unique elements like HashSet. In TreeSet, access and retrieval time are faster.

Map Interface

The Map interface in the Java Collections Framework represents a collection of key-value pairs. In the Map interface, each key is unique and maps to a corresponding value. It is useful when we need to perform operations such as looking up values by their associated keys, adding or removing key-value pairs, and iterating over the keys or values in the map.

Map Interface

Some of the methods in map interface are,

  • put(K key, V value): Put the value with the key in the map. If the map already contains a mapping for the key, the old value is replaced.
  • get(Object key): Get the value associated with the given key in the map. It returns null if the map contains no mapping for the key.
  • remove(Object key): Removes the mapping for the specified key from the map, if there is a mapping.
  • containsKey(Object key): Check whether the map contains the given key.
  • containsValue(Object value): Check whether the map contains mappings to the specified value.
  • keySet(): Get a Set view of the keys in the map.
  • values(): Get a Collection view of the values in the map.
  • entrySet(): Get a Set view of the mappings in the map.

Map interface is implemented by several classes in the Java library, including HashMap, TreeMap, and LinkedHashMap.

HashMap

HashMap<Type, Type> hashMap = new HashMap<>();

HashMap implements the Map interface. It provides a way to store and manipulate key-value pairs, where each key is unique and maps to a corresponding value. HashMap uses a hash table to store the key-value pairs, which provides fast access to the elements. One object is used as a key to another object. HashMap is almost similar to Hashtable except that it’s unsynchronized and allows null keys and values.

LinkedHashMap

HashMap<Type, Type> linkedHashMap = new LinkedHashMap<>();

LinkedHashMap is a class in the Java Collections Framework that implements the Map interface and extends the HashMap class. It provides a way to store and manipulate key-value pairs, in which each key is unique and maps to a corresponding value while also maintaining the order of insertion of the key-value pairs.

SortedMap Interface

The SortedMap interface is a subinterface of Map interface that provides a way to store and manipulate key-value pairs, where each key is unique and maps to a corresponding value while maintaining the keys in sorted order. The SortedMap interface extends the Map interface and adds methods to access the elements in sorted order based on the natural ordering of the keys or a custom Comparator that is provided.

TreeMap

SortedMap<Type, Type> treeMap= new TreeMap<>();

TreeMap implements the SortedMap interface. It provides a way to store and manipulate key-value pairs. In TreeMap, each key is unique and maps to a corresponding value while maintaining the keys in sorted order.

TreeMap is implemented using a Red-Black Tree data structure, a self-balancing binary search tree. This allows TreeMap to provide efficient time complexity for basic operations on the map, such as put, get, and remove. TreeMap can also efficiently perform operations such as range queries using the subMap, headMap, and tailMap methods provided by the SortedMap interface.

Post a comment