Collection Hierarchy in Java
In this tutorial, we will know another important topic collection hierarchy in Java and collection interface.
Collection Hierarchy defines the relationships among various interfaces and classes that build up the Java Collections framework. It enables programmers to efficiently store, manipulate, and process data in Java.
The hierarchy of the entire collections framework consists of four core interfaces such as Collection, List, Set, Map, along with two specialized interfaces named SortedSet and SortedMap for sorting.
All the interfaces and classes of the collections framework are located in java.util package. The diagram of Java collection hierarchy is shown in the below figure.
e➝ extends, I➝ implements
In the diagram of collection hierarchy,
- Extends: This is a keyword that is used for developing inheritance between two classes and two interfaces.
- Implements: This is a keyword used for developing inheritance between class and interface.
Core Interfaces of Collection Hierarchy in Java
The entire collection hierarchy in Java mainly consists of around four core interfaces and two specialized interfaces:
- Collection Interface
- List Interface
- Set Interface
- Queue Interface
- Map Interface
- Specialized Interface
- SortedMap
- NavigableMap
Let’s briefly understand each collection interface in the collection hierarchy of Java.
Collection Interface
- The Collection interface is the root interface of the Java Collections Framework. It is the root of most of the collections API (Application Programming Interface).
- This interface defines the basic operations that all collection classes must implement.
- The collection interface is placed at the top of the collection hierarchy in Java.
- It provides the basic methods for performing operations like adding, removing, and accessing elements in a collection.
- The Collection interface extends the Iterable interface.
- The Iterable interface contains only one method, called iterator(). The function of iterator method is to return an Iterator object. Using this iterator, we can traverse (iterate) over the elements of a collection one by one.
- The List, Queue, and Set interfaces are the three interfaces that extend the Collection interface, forming its three main sub-interfaces.
- The Map interface is not inherited from the Collection interface because it represents a collection of key-value pairs, which is conceptually different from other collection types.
List Interface
- The List interface represents an ordered collection of elements whose elements are arranged sequentially ordered.
- List maintains an order of elements, meaning that the order is retained in which we add elements, and the same sequence we will get while retrieving elements.
- In a list, you can insert, access, or remove elements from any location (index).
- The list interface allows storing duplicate elements in Java.
- The three main concrete subclasses that implement the List interface are:
- ArrayList
- LinkedList
- Vector
- (and its subclass Stack)
Set Interface
- The Set interface represents a collection of elements that contains unique elements. This interface is used to store the collection of unique elements.
- A Set does not maintain any order while storing elements. While retrieving, the order of elements may differ from the order in which you put elements. In simple terms, all the elements in a set can be in any order.
- Set does not allow any duplicate elements in the collection.
- Three common classes that implement the Set interface are:
- HashSet
- LinkedHashSet
- TreeSet
- The SortedSet interface extends Set interface.
- A Set can be iterated using an Iterator, but cannot be iterated using a ListIterator, since it does not maintain index-based ordering like a List.
SortedSet Interface
- The SortedSet interface extends the Set interface and maintains its elements in ascending (natural) order or according to a custom comparator provided at the time of creation.
- The TreeSet class implements the SortedSet interface and automatically sorts its elements in natural or specified order.
Queue Interface
- A queue is an ordered of the homogeneous group of elements in which new elements are added at one end(rear) and elements are removed from the other end(front). Just like a queue in a supermarket or any shop. This follows the FIFO (First-In, First-Out) principle.
- The Queue interface represents a special type of collection in which elements are retrieved in a specific order usually from the head.
- Common concrete subclasses that implement the Queue interface include:
- LinkedList
- PriorityQueue
- ArrayDeque
- PriorityBlockingQueue
- LinkedBlockingQueue
Deque Interface
- A Deque (Double-Ended Queue) is a sub-interface of Queue interface. It is usually pronounced “deck”.
- The Deque interface was added to the Collections Framework in Java SE 6.
- This interface allows elements to be inserted and removed from both ends (front and rear).
- The Deque interface extends the Queue interface and provides additional methods to support insertion, removal, and retrieval of elements from both ends. You can insert and remove elements from either end.
- Two common sub-classes that implement the Deque interface include:
- ArrayDeque
- LinkedList
- The hierarchy diagram of the Deque interface is shown in the below figure.
Map Interface
- The Map interface is not inherited by the Collection interface. That is, it is not a child of the Collection interface.
- It represents an object that stores and retrieves elements in the form of a Key/Value pairs, where each key is unique and is used to retrieve its corresponding value.
- The position (or location) of elements in a Map is determined by their keys.
- Map uses a hashing technique for storing key-value pairs efficiently.
- It doesn’t allow to store the duplicate keys, but duplicate values are allowed.
- Common concrete subclasses that implement the Map interface include:
- HashMap
- Hashtable
- LinkedHashMap
- TreeMap
- The hierarchy of the Map interface is shown in the below figure.
SortedMap Interface
- The SortedMap interface represents a Map whose entries are stored in ascending order of keys (i.e. natural ordering) or according to a custom comparator provided at creation.
- It extends the Map interface which in turn is implemented by TreeMap class.
Methods of Collection Interface in Java
The Collection interface in Java provides a set of methods to manipulate elements in a collection. In total, it consists of 15 core methods, which are used for adding, removing, querying, and iterating over elements.
1. add():
- This method is used to add or insert an element in the collection.
- If the element is added to the collection, it will return true. Otherwise, returns false, if the element is already present and the collection doesn’t allow duplicates.
- The general syntax of add() method is as follow:
add(Object element) : boolean
2. addAll():
- This method adds a collection of elements to the collection.
- The addAll() method returns true if the elements are added. Otherwise, it returns false.
- The general syntax of addAll() method is as follows:
addAll(Collection c) : boolean
3. clear():
- The clear() method clears or removes all the elements from the collection.
- This method returns nothing.
- The general form of this method is as follows:
clear() : void
4. contains():
- The contains() method checks that element is present or not in a collection. That is, it is used to search an element.
- This method returns true if the element is present otherwise false.
- The general for contains() method is as:
contains(Object element) : boolean
5. containsAll():
- The containsAll() method checks that specified a collection of elements are present or not.
- It returns true if the calling collection contains all specified elements. Otherwise, it return false.
- The general syntax of containsAll() method is as follows:
containsAll(Collection c) : boolean
6. equals():
- The equals() method checks for equality with another object.
- The general form of this method is as follows:
equals(Object element) : boolean
7. hashCode():
- The hashCode() method returns the hash code number for the collection.
- Its return type is an integer.
- The general form for this method is:
hashCode() : int
8. isEmpty():
- The isEmpty() method returns true if a collection is empty. That is, this method returns true if the collection contains no elements.
isEmpty() : boolean
9. iterator():
- This method returns an iterator.
- The general form is given below:
iterator() : Iterator
10. remove():
- The remove() method removes a specified element from the collection.
- This method returns true if the element was removed. Otherwise, it returns false.
- The general syntax is given below:
remove(Object element) : boolean
11. removeAll():
- The removeAll() method removes all elements from the collection.
- It returns true if all elements are removed otherwise returns false.
removeAll(Collection c) : boolean
12. retainAll():
- This method is used to remove all elements from the collection except the specified collection.
- It returns true if all the elements are removed otherwise returns false.
retainAll(Collection c) : boolean
13. size():
- The size() method returns the total number of elements in the collection.
- Its return type is an integer.
- The general syntax is given below:
size() : int
14. toArray():
- The toArray() method returns the elements of a collection in the form of an array.
- The array elements are copies of the collection elements.
toArray() : Object[]
15. Object[ ] toArray():
- Returns an array that contains all the elements stored in the invoking collection.
- The array elements are the copies of the collection elements.
toArray(Object array[]) : Object[]
Collection Classes in Java
The collections classes implement the collection interfaces. They are defined in java.util package. Some of these classes provide full implementations that can be used as it is. While, others are abstract classes that provide basic implementations and can be extended to create concrete collections.
A brief overview of the main concrete and abstract collection classes in the Java Collection hierarchy is given below.
1. AbstractCollection:
- The AbstractCollection class implements most of the Collection interface. It is a superclass for all of the concrete collection classes.
2. AbstractList:
- This class extends AbstractCollection and implements most of the List interface.
3. AbstractQueue:
- This collection class extends AbstractCollection and implements the Queue interface.
4. AbstractSequentialList:
- The AbstractSequentialList class extends AbstractList and provides a framework for list implementations that use sequential order to access elements.
5. AbstractSet:
- Extends AbstractCollection and implements most of the Set interface.
6. ArrayList:
- The ArrayList class extends AbstractList and implements a dynamic array that allows random access of elements.
7. EnumSet:
- This collection class extends AbstractSet and is designed specifically for use with enum elements.
8. HashSet:
- Extends AbstractSet and uses a hash table for storing elements.
9. LinkedHashSet:
- Extends HashSet to allow insertion-order iterations.
10. LinkedList:
- The LinkedList class extends AbstractSequentialList and implements a doubly linked list.
11. PriorityQueue:
- This collection class extends AbstractQueue to support a priority-based queue where elements are ordered according to their natural order or a custom comparator.
12. TreeSet:
- The TreeSet class extends AbstractSet and implements the SortedSet interface to store elements in the sorted order.
Key Points of Collection Hierarchy in Java
Some key points of the collection hierarchy in Java that you should keep in mind are as follows:
- The core interfaces in collection hierarchy are List, Set, Queue, and Map.
- The key implementation classes in the collection hierarchy include ArrayList, LinkedList, HashSet, TreeSet, PriorityQueue, HashMap, and TreeMap.
- The most commonly used methods of collection interface include add(), remove(), size(), isEmpty(), contains(), and clear().
- All collection interfaces and classes are part of the java.util package.
- The Map interface is not a child of the Collection interface. It is part of the Collections Framework and represents a separate hierarchy.