The package java.util contains one of the Java’s most powerful subsystems: the
Collections Framework. The Collections Framework is a modern chain of the importance of interfaces and classes that give cutting-edge innovation for managing the group of objects. With the beginning of JDK 9, java.util is now a part of the java.base module. Due to its significance, this technology is in demand and is always asked during the selection process of the Java candidates applying for the job. So, in this journal entry, we have focused on top 10 java collections interview questions and answers for your quick reference.
Top 10 Java Collections Interview Questions and Answers
Collections have become the de-facto standard for every programming language nowadays. However, the initial Java release does not collections but contained few classes for collections: Dictionary, Vector, Stack, and Properties. But looking at the larger scope and usage, Java 1.2 came up with Collections Framework that group all the collections interfaces, implementations and algorithms. Java Collections have come a long way with usage of Generics and Concurrent Collection classes for threadsafe operations. It also includes blocking interfaces and their implementations in java concurrent package.
Some of the benefits of collections framework are:
- Reduced development effort by using core collection classes rather than implementing our own collection classes.
- Code quality is enhanced by the use of well-tested collections framework classes.
- Reduced effort for code maintenance by using collection classes shipped with JDK.
- Reusability and Interoperability.
There are three generic types of collection:
Ordered lists: Ordered lists allows the programmer to insert items in a certain order and retrieve those items in the same order. An example is a waiting list. Two interfaces are included in the Ordered Lists which are the List Interface and the Queue Interface.
Dictionaries/Maps: Dictionaries/Maps store references to objects with a lookup key to access the object’s values. One example of a key is an identification card. The Map Interface is included in the Dictionaries/Maps.
Sets: Sets are unordered collections that can be iterated and where similar objects are not allowed. The Interface Set is included.
An iterator is an interface that offers a general-purpose, standardized way of accessing the elements within a collection, one at a time. Each collection in the Collections framework provides an iterator and we can get the instance using the iterator() method.
JDK 8 added another type of iterator called a Spliterator. In brief, spliterators are iterators that provide support for parallel iteration. The interfaces that support spliterators are Spliterator.
Maps store key/value pairs. Although Map interfaces and its implementations are part of Collections Framework, Maps are not collections and collections are not Map. Maps don’t implement the Iterable interface, this means that we cannot cycle through a map using a for-each style for loop. Furthermore, we can’t obtain an iterator to a map. However, we can obtain a collection-view of a map by retrieving the list of Keys or Values, which does allow the use of either the for loop or an iterator.
Recommended Read:
- Understanding HashMap in Java
- Understanding HashTable in Java
- What Is The Difference Between HashMap And HashTable?
- Difference Between ArrayList And LinkedList
- Top Java Interview Question And Answers
Generics were introduced with Java 1.5 and since its inception, all collection interfaces and implementations use it heavily. They allow us to provide the type of Object that a collection can contain, so when we try to add any other type of element it will throw a compile time error. This avoids ClassCastException at Runtime because you will get the error at compilation. Also, Generics make code clean since we don’t need to use casting and instanceof operator.
- ListIterator is inherited from the Iterator interface but it comes with some extra functionalities, like adding or replacing an element, getting the index position of the previous and next element.
- Iterator can be used to traverse Set and List collections whereas ListIterator can only be used with Lists.
- Iterator is unidirectional, i.e., we can traverse in forwarding direction only. Whereas ListIterator is bidirectional, i.e., we can traverse the list in both directions.
We can iterate over a list in two different ways – using the for-each loop or by using the Iterator. Using an Iterator is more thread-safe because it makes sure that if underlying list elements are modified, it will throw ConcurrentModificationException
.
List<String> strList = new ArrayList<>(); //using for-each loop for(String obj : strList){ System.out.println(obj); } //using iterator Iterator<String> it = strList.iterator(); while(it.hasNext()){ String obj = it.next(); System.out.println(obj); }
Fail-Safe property of the Iterator works with the clone of underlying collection. Hence, it’s not affected by any modification done in the collection.
Fail-Fast property of the Iterator checks for any modification in the structure of the underlying collection every time we try to get the next element. If there are any modifications found, it throws ConcurrentModificationException
. All the implementations of Iterator in Collection classes are fail-fast by design except the concurrent collection classes like ConcurrentHashMap and CopyOnWriteArrayList.
By design, all the collection classes in java.util package is fail-fast whereas collection classes in java.util.concurrent are fail-safe like ConcurrentHashMap and CopyOnWriteArrayList.
java.util.concurrent.BlockingQueue
is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.
BlockingQueue interface is part of java collections framework and it’s primarily used for implementing producer-consumer problem. We don’t need to worry about waiting for the space to be available for producer or object to be available for the consumer in BlockingQueue as it’s handled by implementation classes of BlockingQueue.
Java provides several BlockingQueue implementations such as ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue etc.
Recommended Read: