In our previous posts, we have learned about OOPS concepts, Java string, and other core java tutorials. Now, let’s start learning some of the advanced concepts of Java programming language, i.e. Java Collection Framework.
the Java programming language supports Arrays to store several objects in it but when we have initialised an array with predefined size during instantiation. We Can store groups of objects in an array and also retrieve easily, but there are some inconveniences, that are:
- We can not store different class objects into the same array. The reason is an array can store only one data type of elements.
- Adding the objects at the end of an array is easy but inserting and deleting the elements in the middle of an array is difficult. That case, we have to rearrange the elements of the array.
- Retrieving elements from an array is easy, but if you want to process them, then there are no methods available to carry out this.
Due to the above problems, programmers want a better mechanism to store a group of objects. The alternative way is using an object to store a group of other objects. That means we can use a class object as an array, such an object is called “collection object” or “container object”, and for more flexible data structures the core java library provides the collection framework.
What is a Java Collection Framework?
A Java collection framework provides an architecture to store and manipulate a group of objects. A Java collection framework has the following things in it:
Interfaces: Interfaces provides an abstract data type to represent collection and java.util.collection is the root interface of the collection framework. and the collection interface also contains some methods like size(), iterator(), add(), remove() and clear() etc so that every collection class should implement those methods and also some interfaces like java.util.List, java.util.Set, java.util.Queue and java.util.Map.
The map is the only interfaces which do not inherit from the collection interface, but it’s part of the collection framework. All the interfaces of the collection framework are present inside Java. util package.
Implemented Classes: Collections in Java provide the implementation of the collection interface. There are some important classes are ArrayList, LinkedList, HashMap, TreeMap, HashSet, TreeSet. These classes help to solve our most of programming need, but if we need some more unique features, then we need to extend them and then create our custom collection class. All the collection classes present inside java. util package.
Algorithm: It is referring to the methods which we are used to performing the operations like sorting, searching on the objects those implements collection interface.
Benefits of Java Collection Framework
Here are the benefits of the Java collection framework:
- Reduced Development Effort: As it has all common types of collections and useful methods which helps in iterate and manipulate the data, so we can concentrate more on how to develop the business logic rather than in designing collection API.
- Increased Quality: The Collection classes are well tested, so it helps to increase our program quality rather than using home developed data structure.
Java Collection Framework Hierarchy
As we have learned that Java collection framework which has combinations of Interfaces and classes. Let’s understand that collection framework hierarchy for better understands about the framework.
Java Collections Interfaces
As we saw in the above picture, the collection framework is a combination of classes and interfaces. On the total framework collection interface is the root interface for the Java collection framework, and the collection interface is generic.
For example public interface Collection<E>.
When we declare a collection interface, we need to specify the type of object it can contain so we can mention <E> in the above syntax, and the <E> syntax is for Generics.
The Java Collection framework contains the below interfaces:
- Collection Interface
- List Interface
- Set Interface
- SortedSet Interface
- NavigableSet Interface
- Queue Interface
- Map Interface
- SortedMap Interface
- Navigable Map Interface
The root interface for the Java collection framework is a collection interface. A collection represents a group of objects known as its elements. The Java programming language doesn’t provide any direct implementation of this interface.
The Interface has different methods in it, those are:
- contains() – To Check whether the object is present in the collection or not
- add() and remove() – to add or remove element from the collection
- iterator() – it helps to iterate elements of the collection
The collection interface also has some bulk operations methods which work over the entire collection. Those methods are:- containsAll, addAll, removeAll, retainAll, clear.
There is another method present in the collection interface, which is toArray(), this method act as a bridge between collections and Older API, which expect arrays on Input.
Important Points about Collection Interface
- If we want to represent a group of individual objects as a single entity, then we should go for the collection.
- Collection interface defines the most common methods which are applicable for any collection objects.
- In general collection, the interface is considered as the root interface of the collection framework.
- There is no concentrate class which implements collection interface directly.
Difference between Collection & Collections
|The collection is an interface||Collections is a utility class.|
|If we want to represent a group of individual objects as a single entity, then we should go for the collection.||Collections present in java.util package and it has so many utility methods for collection objects like sorting, searching, etc.|
- It is the child interface of collection.
- If we want to represent a group of an individual object as a single entity where duplicates are allowed, and insertion order must be preserved then we should go for the List.
- You can access the elements by using the index and also the size of a List interface is dynamic.
- The implementation classes of List interface is ArrayList and LinkedList.
- It is the child interface of collection.
- If we want to represent a group of the individual object as a single entity where duplicates are not allowed and insertion order not preserved, then we should go for the List.
- The size of the Set will increase dynamically when you add elements to it.
- A Set will not allow duplicate elements, and if you try to insert duplicate elements, then it is not stored into the set.
- In Java, there are three implementation classes of the Set interface that are HashSet, TreeSet and LinkedHashSet.
- The set interface doesn’t allow to random access elements in the collection, but you can use iterator or for-each loop for traversing the elements of a Set Interface.
- SortedSet Interface is a child interface of Set Interface.
- If we want to represent a group of individual objects as a single entity where duplicates are not allowed, and all objects should be inserted according to some sorting order, then we should go for the sorted set.
- It is the child interface of the sorted set.
- It contains several methods for navigation purposes.
- It is the child interface of collection.
- If we want to represent a group of an individual object prior to processing, then we should go for the queue.
- Usually, queue follows First in First Out (FIFO) order that means the element which element is stored as the first element into the queue that will be removed first from the queue. But based on our requirement, we can implement our priority order also.
This Collection interface supports the element insertion and deletion in both the ends. This interface has methods like insert(), remove() and examine the element.
- The map is not a child interface of Collection interface.
- If we want to represent a group of objects as key-value pairs, then we should go for the map if Both key-value is objected only.
- If the key value is provided, then we can retrieve the corresponding value. But the key value should be unique.
- Duplicates keys are not allowed, but values can be duplicated.
- Map interface has three implementation classes like HashMap, TreeMap, and LinkedHashMap.
- The basic operations which we are doing with Map are put, get, containsKey, contains value, size, and isEmpty.
- It is the child interface of Map.
- If we want to represent a group of objects as key-value pairs and want to store them according to some sorting order of keys, then we should go for the sorted map.
- In a Sorted Map, the sorting should be based on the key, but not based on values.
Navigable Map Interface
- It is the child interface of the sorted map.
- It defines several methods for navigation purposes.
- Usually, we can use the collection to hold and transfer objects from one location to another location.
- To provide support for this requirement, every collection class by default implements Serializable and cloneable interface.
- Whereas ArrayList and vector classes implement a random access interface, Because of that when we are trying to access any random element from ArrayList and Vector, we can access with the same speed.
Random access Interface
- Random access interface present in Java.util package and it does not contain any methods.
- It is a marker interface, so whenever needed, the required ability will be provided automatically by JVM.
- ArrayList is the best choice if your frequent operation is retrieval operation. (Because of ArrayList implement random access interface)
- ArrayList is not the correct choice if our frequent operation is the insertion and deletion of the element in the middle.
This interface provides methods by which we can iterate collection elements. For that, we need to create an Iterator instance, and by using that, we can iterate the collection elements and also by using an iterator, you can remove the elements from the collection.
ListIterator is an interface that contains a method to retrieve the elements from the collection object, both in forward and reverse direction. It have following methods: hasNext(), hasPrevious(), next(), previous() and remove().
Its a child interface of Map interface. In this interface, the keys are stored in ascending order.
Java Collections Classes
Java Collection framework has so many implementation classes of a different interface. Out of them, the common implementation classes are ArrayList and HashMap and HashSet. The collection classes are not thread-safe, and their iterator also fails-fast. Below we are trying to share some of the commonly used implementation classes:
Java HashSet is the basic implementation class of the Set interface. It does not guarantee the order of the elements, Duplicate elements are not allowed to be stored, and you can insert null values.
This Classes have methods like add, remove, contains and size. We can also see the initial capacity and load factor for this implementation class. The load factor is a measure of how full the hash map is allowed to get before its capacity is automatically increased.
Java TreeSet class implements the set Interface which uses a tree for storage. This TreeSet class inherits the abstract also and implements NavigableSet Interface. In Tree set, the elements are storing in ascending order, and duplicated elements are not allowed.
Java ArrayList class inherits an abstract class and also implements the list interface, and this class used a dynamic array to store the elements. This is used to store similar elements. As for a standard Array, we need to declare the size of the array before we use it and once the size is declared it’s fixed, but in case of ArrayList we do not need to declare the size its grow as we are adding the elements into it.
The Java LinkedList Class used a double linked list to store the elements. Here the elements are stored as a data part and address part, and each element is known as a node. Due to the ease of insertion and deletion, LinkedList is preferred over arrays. The LinkedList class implements the list interface.
The HashMap Class used a hashtable and implemented the map interface. You can do that all map operations and also it permits null values and null keys. This HashMap Class is almost equivalent to Hashtable except it is synchronised and also permits null\.
TreeMap class implements the Map interface. It also extends the abstract map and implements the NavigableMap interface. This TreeMap class is a red-black tree-based implementation. You can store the key-value pairs in sorting order.
As we have discussed above that the elements of the queues in FIFO order, but sometimes we want to process the elements in priority order. In that case, the priority queue helps to process the elements and priority queue does not allow null values.
The collection class implements the collection interface, which is defined inside the java. util package. In this class, some of the classes with providing full implementations which can be used as it is, and some of them are abstract which need to be fully implementations to create concentrate collections.
This class contains methods for collection framework such as binary search, sorting, shuffling and reverse, etc.
Collections API Algorithms
The collection framework also provides some of the implementations of algorithms which are commonly used like Sorting and searching. Most of the method have algorithms implementations and which are work on the list and some of them for collections.
By using these algorithms, users can sort the elements in ascending order. There are two forms of this operation provided one is making a list and sort its elements in ascending order of elements with natural ordering. The second form is sorting the elements with the help of comparator.
This helps in destroying the sorting order if the list elements have in any order. This algorithm helps in implementing in games.
This searching algorithm helps to find the specified elements in a sorted list. This algorithms also have two forms where it takes a list and the search element, but it assumes the list elements are in sorted order. The second form is taking a comparator with the list and search item and assumed the list is in sorted into ascending order according to the specified comparator. Here the sort algorithms are called first to sort the elements before calling binary search.
Min and Max values
These two algorithms find the max and min elements of the collection. This algorithms also comes in two forms. the first takes a natural ordering of elements are return the maximum or minimum elements from the collection and the second form is taking a comparator with the collection and return the maximum or minimum elements according to the specified comparator.