Java Collection Interview Questions and Answer

Here is a list of Java Collections interview Questions. These are some of the famous questions asked in interviews.

Java Collections Interview Questions

What is the Java Collections Framework?

The Java Collections Framework is a set of interfaces and classes that provide a foundation for working with collections of objects. It offers reusable data structures, such as lists, sets, and maps, as well as algorithms for manipulating these structures.

What are the main benefits of using the Java Collections Framework?

The main benefits of using the Java Collections Framework are code reusability, improved performance, reduced development effort, and increased code quality.

What is the difference between Collection and Collections in Java?

“Collection” is an interface in the Java Collections Framework that serves as the base for all collection types, such as List, Set, and Queue. “Collections,” on the other hand, is a utility class that provides static methods for performing operations on collections, such as sorting, searching, and reversing.

What is the difference between a stack and a queue in Java?

A stack and a queue are two different data structures that store elements in different orders:

  • Stack: A stack follows the LIFO (Last In, First Out) principle, meaning the last element added to the stack is the first one to be removed. You can use the push() method to add elements and the pop() method to remove elements from the stack.
  • Queue: A queue follows the FIFO (First In, First Out) principle, meaning the first element added to the queue is the first one to be removed. You can use the add() or offer() methods to add elements and the remove() or poll() methods to remove elements from the queue.

In Java, you can use the java.util.Stack class to represent a stack, and the java.util.Queue interface along with its implementations, such as LinkedList, to represent a queue.

What is the difference between HashSet, TreeSet, and LinkedHashSet in Java?

HashSet, TreeSet, and LinkedHashSet are three implementations of the Set interface in Java:

  • HashSet: Uses a hash table to store elements. It offers constant-time insertion, deletion, and search operations but does not maintain any order among elements.
  • TreeSet: Uses a balanced binary search tree (a Red-Black tree) to store elements. It maintains elements in their natural order (or according to a specified Comparator) but has O(log n) time complexity for insertion, deletion, and search operations.
  • LinkedHashSet: Extends HashSet but maintains the insertion order of elements using a doubly-linked list. It offers constant-time insertion and deletion operations, and iteration is faster than TreeSet but slower than HashSet.

What i the difference between HashMap, TreeMap, and LinkedHashMap in Java?

HashMap, TreeMap, and LinkedHashMap are three implementations of the Map interface in Java:

  • HashMap: Uses a hash table to store key-value pairs. It offers constant-time insertion, deletion, and search operations but does not maintain any order among keys.
  • TreeMap: Uses a balanced binary search tree (a Red-Black tree) to store key-value pairs. It maintains keys in their natural order (or according to a specified Comparator) but has O(log n) time complexity for insertion, deletion, and search operations.
  • LinkedHashMap: Extends HashMap but maintains the insertion order of keys using a doubly-linked list. It offers constant-time insertion and deletion operations, and iteration is faster than TreeMap but slower than HashMap.

More Java Collection Interview Questions

What is an Iterator in Java?

An Iterator is an interface in the Java Collections Framework that provides a way to traverse elements of a collection. It has methods like hasNext(), next(), and remove(). All Java Collection classes provide iterator() methods to obtain an Iterator instance for traversing their elements.

What is a fail-fast iterator?

A fail-fast iterator is an iterator that throws a ConcurrentModificationException if it detects that the underlying collection has been modified while the iterator is still in use. This behavior is intended to prevent unpredictable results when multiple threads are accessing the same collection. Examples of fail-fast iterators include those provided by ArrayList, HashSet, and HashMap.

What is a fail-safe iterator?

A fail-safe iterator is an iterator that does not throw a ConcurrentModificationException if the underlying collection is modified while the iterator is in use. Instead, it works on a snapshot of the collection, ensuring that the iterator does not encounter any unexpected changes to the collection. Examples of fail-safe iterators include those provided by the classes in the java.util.concurrent package, such as ConcurrentHashMap and CopyOnWriteArrayList.

What is the difference between Comparable and Comparator interfaces in Java?

Comparable and Comparator are two interfaces in Java that define how objects should be compared for sorting and ordering purposes:

  • Comparable: Objects that implement the Comparable interface can be compared to other objects of the same type. The compareTo() method must be implemented, which compares the current object to another object and returns a negative, zero, or positive integer depending on whether the current object is less than, equal to, or greater than the other object. Implementing Comparable allows objects to be sorted using Arrays.sort() or Collections.sort() methods.
  • Comparator: A separate class that implements the Comparator interface can define a custom comparison logic for objects of another class. The compare() method must be implemented, which takes two objects as arguments and returns a negative, zero, or positive integer depending on their relative order. Using a Comparator allows sorting objects without modifying the original class and provides the flexibility to use different sorting criteria.

What is the use of the Collections.synchronized* methods?

The Collections.synchronized* methods, such as synchronizedList(), synchronizedSet(), and synchronizedMap(), are used to create thread-safe wrapper objects around the specified collections. These wrapper objects ensure that all access to the underlying collection is synchronized, preventing data corruption when multiple threads concurrently modify the collection.

However, these synchronized wrappers have some limitations. For example, they do not guarantee atomicity for compound operations like iteration, and their performance can be significantly slower compared to non-synchronized collections. In such cases, using java.util.concurrent collections like ConcurrentHashMap or CopyOnWriteArrayList is recommended.

What is the difference between List, Set, and Map in Java?

This Java collection interview question has been asked so many times. List, Set, and Map are three main interfaces in the Java Collections Framework:

  • List: Represents an ordered collection of elements that can contain duplicates. Examples of List implementations include ArrayList and LinkedList.
  • Set: Represents an unordered collection of unique elements. Examples of Set implementations include HashSet, TreeSet, and LinkedHashSet.
  • Map: Represents a collection of key-value pairs, with each key being unique. Examples of Map implementations include HashMap, TreeMap, and LinkedHashMap.

What is the difference between ArrayList and LinkedList in Java?

ArrayList and LinkedList are two implementations of the List interface in Java:

  • ArrayList: Uses a dynamic array to store elements. It offers constant-time access to elements by index, but inserting or deleting elements may require resizing and copying the array, which can be slow.
  • LinkedList: Uses a doubly-linked list to store elements. It offers constant-time insertion and deletion of elements, but accessing elements by index can be slower as it requires traversing the list.

What is the difference between HashMap, LinkedHashMap, and TreeMap in Java?

HashMap, LinkedHashMap, and TreeMap are three popular classes in Java that implement the Map interface. They differ in their ordering and performance characteristics:

  • HashMap: It stores key-value pairs in an unordered manner. It uses a hashing mechanism to determine the storage location for each key-value pair. HashMap provides constant-time performance (O(1)) for basic operations like get() and put() under ideal conditions. However, its performance can degrade if there are hash collisions.
  • LinkedHashMap: It extends HashMap and maintains the insertion order of key-value pairs. This order can be used for iteration purposes. LinkedHashMap has the same performance characteristics as HashMap but with a slightly higher memory overhead.
  • TreeMap: It stores key-value pairs in a sorted order based on their keys. It uses a Red-Black Tree data structure to store elements. TreeMap provides logarithmic time performance (O(log n)) for basic operations like get() and put(). TreeMap is a good choice when you need to maintain a natural order of keys.

What is the difference between HashSet, LinkedHashSet, and TreeSet in Java?

HashSet, LinkedHashSet, and TreeSet are three popular classes in Java that implement the Set interface. They differ in their ordering and performance characteristics:

  • HashSet: It stores unique elements in an unordered manner. HashSet uses a hashing mechanism to determine the storage location for each element. It provides constant-time performance (O(1)) for basic operations like add(), remove(), and contains() under ideal conditions.
  • LinkedHashSet: It extends HashSet and maintains the insertion order of elements. This order can be used for iteration purposes. LinkedHashSet has the same performance characteristics as HashSet but with a slightly higher memory overhead.
  • TreeSet: It stores unique elements in a sorted order based on their natural order or a custom comparator. It uses a Red-Black Tree data structure to store elements. TreeSet provides logarithmic time performance (O(log n)) for basic operations like add(), remove(), and contains(). TreeSet is a good choice when you need to maintain a sorted order of elements.

What is the difference between List and Set in Java?

List and Set are two primary interfaces in the Java Collections Framework:

  • List: It is an ordered collection that allows duplicates. The elements in a List can be accessed by their index positions, and the order of elements is maintained during insertion. Some popular List implementations include ArrayList and LinkedList.
  • Set: It is an unordered collection that does not allow duplicate elements. It is used when you need to store a unique set of elements without any specific order. Some popular Set implementations include HashSet, LinkedHashSet, and TreeSet.

How can you remove duplicates from a List in Java?

To remove duplicates from a List in Java, you can use a Set. Here’s an example:

This code snippet first creates a HashSet from the original List, which removes duplicates due to the uniqueness property of the Set. Then, it creates a new ArrayList from the HashSet, resulting in a List without duplicates.

What is the difference between Iterator and ListIterator in Java?

Iterator and ListIterator are two interfaces in Java used for iterating over collections:

  • Iterator: It is a universal iterator that can be used with any Collection implementation. Iterator allows you to traverse a collection in a forward direction and remove elements during iteration. The primary methods provided by Iterator are hasNext(), next(), and remove().
  • ListIterator: It is a specialized iterator that can only be used with List implementations. ListIterator extends Iterator and provides additional functionality, such as bidirectional traversal (forward and backward), adding elements, and accessing elements by index. The primary methods provided by ListIterator include hasNext(), next(), hasPrevious(), previous(), add(), set(), and remove().

What is the difference between ArrayList and LinkedList in Java?

ArrayList and LinkedList are two popular List implementations in Java, each with its own performance characteristics:

  • ArrayList: It uses a dynamic array to store elements, which allows for constant-time access (O(1)) but may require resizing when adding or removing elements. ArrayList is ideal when you have more get() and set() operations and fewer add() and remove() operations.
  • LinkedList: It uses a doubly-linked list to store elements, which allows for constant-time insertion and removal (O(1)) at the beginning and end of the list but requires linear-time access (O(n)). LinkedList is a good choice when you have more add() and remove() operations and fewer get() and set() operations, especially if the modifications are at the beginning or end of the list.

What is a ConcurrentModificationException, and how can you avoid it in Java?

ConcurrentModificationException is a runtime exception that occurs when a collection is modified while it is being iterated. This exception is thrown to prevent unpredictable and undesirable behavior.

To avoid ConcurrentModificationException, you can use one of the following approaches:

  • Use an Iterator and its remove() method to modify the collection while iterating.
  • Use a CopyOnWriteArrayList or CopyOnWriteArraySet, which are thread-safe collection implementations that create a new copy of the collection when modified, allowing for safe iteration even when the collection is modified.
  • Use a ConcurrentHashMap or a ConcurrentSkipListMap, which are thread-safe Map implementations that support concurrent modifications.
  • Synchronize the access to the collection if you are using it in a multithreaded environment.

What is the difference between HashSet, TreeSet, and LinkedHashSet in Java?

HashSet, TreeSet, and LinkedHashSet are three popular Set implementations in Java, each with distinct features and performance characteristics:

  • HashSet: It uses a hash table to store unique elements with no guaranteed order. It offers constant-time performance (O(1)) for basic operations like add(), remove(), and contains(). HashSet is generally faster than TreeSet and LinkedHashSet.
  • TreeSet: It uses a balanced binary search tree (usually a Red-Black tree) to store unique elements in sorted order. It provides O(log(n)) performance for add(), remove(), and contains() operations. TreeSet is slower than HashSet but maintains a sorted order.
  • LinkedHashSet: It is an ordered version of HashSet that maintains a doubly-linked list of elements in the order they were inserted. It provides almost constant-time performance (O(1)) for add(), remove(), and contains() operations. LinkedHashSet is slightly slower than HashSet but maintains insertion order.

What is the use of the Collections class in Java?

The Collections class in Java is a utility class that provides various static methods to perform operations on collections such as Lists, Sets, and Maps. Some of the commonly used methods provided by the Collections class are:

  • sort(): Sorts a List using the natural order of its elements or according to the specified Comparator.
  • reverse(): Reverses the order of elements in a List.
  • shuffle(): Randomly shuffles the elements in a List.
  • min() and max(): Finds the minimum and maximum element in a collection according to their natural order or a specified Comparator.
  • frequency(): Counts the occurrences of a specified element in a collection.
  • synchronizedList(), synchronizedSet(), and synchronizedMap(): Wraps a collection with a synchronized (thread-safe) collection, which can be used in a multithreaded environment.

How do you create an immutable collection in Java?

Immutable collections are collections that cannot be modified once they are created. You can create an immutable collection in Java using the following methods:

  • Collections.unmodifiableList(), Collections.unmodifiableSet(), and Collections.unmodifiableMap(): These methods wrap a given collection with an unmodifiable view, making it read-only.
  • Java 9 introduced factory methods for creating immutable collections: List.of(), Set.of(), and Map.of() or Map.ofEntries(). These methods return immutable collections containing the specified elements.

What is the difference between fail-fast and fail-safe iterators in Java?

Fail-fast and fail-safe iterators are two types of iterators in Java that handle concurrent modifications differently:

  • Fail-fast iterators: These iterators immediately throw a ConcurrentModificationException if the underlying collection is modified while iterating. Most iterators provided by the Java Collections Framework, such as ArrayList, HashSet, and HashMap, are fail-fast.
  • Fail-safe iterators: These iterators do not throw any exception if the underlying collection is modified while iterating. Instead, they work on a copy of the collection, isolating them from any changes made to the original collection. Examples of fail-safe iterators are iterators provided by the ConcurrentHashMap and CopyOnWriteArrayList classes.

What is rehashing? When is it done?

In the case of a HashMap, there are two important member fields which determine when exactly the resizing of the map needs to be done. They are loadFactor and capacity. If we don’t specify these two while creating a new HashMap (i.e., we don’t call parameterized constructor that takes these two arguments, but call the no-arg constructor), the new HashMap will be created with default loadFactor of 0.75 and default initial capacity of 16.
As soon as the size of the Map grows and reaches 75%, it would construct a new Map with 50% more capacity than the current capacity. The elements of the HashMap are copied after doing a new hash on the newly constructed HashMap. This process is known as rehashing.

 

How does the HashMap’s Iterator detect a modification and throw ConcurrentModificationException?

HashMap’s iterator is a fail-fast iterator. It means, if any modification is done on the underlying collection during iteration, then the iterator should stop iterating and throw ConcurrentModificationException. HashMap achieves this by keeping track of the number of modifications. HashMap has an internal integer member field named modCount. This is incremented each time a user invokes methods like put(), remove(), putAll(), clear(), etc  modifying the data structure. When the iterator is created, a similar field maintained in Iterator implementation class called iteratorModCount is initialized with HashMap’s modCount. During iteration, these values are checked, and ConcurrentModificationException is thrown if they are not equal.

Why Map interface does not extend java.util.Collection?

Map interface requires a Key as well as Value for its operations, but Collection requires only one parameter. The keyset() and values() operation provide the keys and values stored in a map, but there are not functions similar to this in java.util.Collection. Due to this incompatibility, Map interface does not extend java.util.Collection.

What is a hash collision? How is it handled in case of a HashMap or a HashTable?

For HashMap or a HashTable, the appropriate bucket in which the Entry<K,V> data shall go during a Map.put(K,V) operation is determined by using K.hashCode(). If two keys give the same hashcode, then both the corresponding entries are destined to go under the same bucket. This scenario is known as a hash collision. If such a case occurs, the HashMap or HashTable stores them in the form of a list under the same bucket. While retrieving, K.equals() method is invoked to get the right Entry<K,V> and retrieve the appropriate value from that. You can read the first two questions of Core Java Interview Questions

What is the difference between poll() and remove() in a PriorityQueue?

queue.poll() and queue.remove() retrieves the head element of the queue. The remove() function will throw a NoSuchElementException if the queue is empty at the time of its execution whereas the poll() function returns a null value in a similar case.

What is the difference between ArrayList and a Vector?

Vector is a legacy class. It is synchronized. If Vector reaches its max size, the underlying array that backs the vector is discarded after creating a new array with double the size of the initial array.

ArrayList was introduced in release 1.2. It was added later as a part of collections framework enhancements. It is not synchronized. If the ArrayList is about to reach its maximum capacity, the underlying array that backs the ArrayList is discarded after creating a new Array with 50% more size than the original Array.

What are the key interfaces in the Java Collections Framework?

The key interfaces in the Java Collections Framework are:

  • Collection: The root interface of the Collections Framework. It represents a group of objects.
  • List: An ordered collection that allows duplicates and provides positional access to elements.
  • Set: An unordered collection that does not allow duplicates.
  • SortedSet: A Set that maintains its elements in a sorted order.
  • Queue: A collection designed for holding elements prior to processing, typically in a FIFO (First In, First Out) order.
  • Deque: A double-ended queue that allows adding and removing elements from both ends.
  • Map: An object that maps keys to values, with no duplicate keys allowed.
  • SortedMap: A Map that maintains its key-value pairs in sorted order based on the keys.

What are the differences between fail-fast and fail-safe iterators in Java?

Fail-fast and fail-safe iterators in Java are two types of iterators that behave differently when the underlying collection is modified during iteration:

  • Fail-fast iterator: It throws a ConcurrentModificationException if the underlying collection is modified while iterating. Most iterators provided by the Java Collections Framework (e.g., ArrayList, HashSet, and HashMap) are fail-fast.
  • Fail-safe iterator: It does not throw any exception if the underlying collection is modified during iteration. Instead, it works on a snapshot or a copy of the underlying collection, so it does not reflect any changes made to the original collection during iteration. Examples of fail-safe iterators include the iterators of CopyOnWriteArrayList, ConcurrentHashMap, and ConcurrentSkipListMap.

What is the difference between a shallow copy and a deep copy of a collection in Java?

A shallow copy of a collection is a new collection containing references to the same elements as the original collection. Modifying the elements in the copied collection will also affect the original collection, as they are still pointing to the same objects.

A deep copy of a collection is a new collection containing copies of the elements in the original collection. The elements in the copied collection are completely independent of the original collection. Modifying the elements in the copied collection will not affect the original collection.

 

How can we iterate over a TreeMap?

There are three ways in which we can iterate over a TreeMap – using for loop for Map.Entry and using iterators for keyset() as well as entrySet().

When would you use a LinkedHashMap?

A LinkedHashMap is one of the implementations available for the Map interface.  LinkedHashMap keeps the order of the insertion of the elements. So LinkedHashMap may be used when a client is expecting that the items are returned in the same order as they are stored.

What is a BlockingQueue?

A BlockingQueue is an implementation of Queue interface. It is available under java.util.concurrent package. It is a thread-safe queue.
A null value is not permitted in a BlockingQueue, and hence it will throw a NullPointerException on any attempt to do so by add, offer or put methods. If the value retrieved is null in case of a queue.poll(), it indicates that something has gone wrong in the BlockingQueue.
BlockingQueue is typically used to solve problems that are similar to the producer-consumer problem.

What is the difference between a ListIterator and an Iterator?

Using an Iterator, we can traverse a List, Set or a Map. In fact, the method iterator() is from the super interface java.util.Collection and concrete classes contain specific implementations to get the iterator for particular Collection interface type. The important methods associated with Iterators are:

  • hasNext()
  • next()
  • remove()

Iterators allow traversal only in the forward direction. ListIterator, as the name suggests, can be used to traverse only a list. An instance of the ListIterator can be obtained by calling List.listiterator(). ListIterator allows you to traverse in both forward and backward directions. Thus, in addition to the above three methods which the ListIterator shares in common with Iterator, the following methods are also added to it:

  • previous()
  • hasPrevious()
  • previousIndex()
  • nextIndex()

A ListIterator does not have the concept of a current element. Its position would always be in between two elements in the list.

What is a WeakHashMap in Java?

A WeakHashMap is a special implementation of the Map interface in Java that stores keys using weak references. This means that if a key is not referenced anywhere else in the application, it can be garbage collected even if it is still present in the WeakHashMap. WeakHashMap is useful for creating caches or storing metadata for objects that should not prevent the objects from being garbage collected.

What is the difference between Collection.remove() and Iterator.remove()?

Collection interface’s remove method has the following signature: public boolean remove(Object o) This method removes the specified element if it is present in the collection and returns true if removal is successful. The function will throw a ClassCastException for an incompatible input, NullPointerException for a null input and UnsupportedOperationException if the underlying collection doesn’t support this operation. Iterator’s remove method has the following signature: public void remove() This method would remove the last element that was returned by the next() call. This method can be called only once per call to the next() method. Otherwise, it would throw an IllegalStateException. In the case of a fail-fast iterator, it will throw an UnsupportedOperationException if remove() is invoked during traversal of the supporting collection.

What is the difference between a HashSet and a TreeSet?

Both HashSet and TreeSet are implementations of the Set interface in Java but have different underlying data structures and characteristics:

  • HashSet: It is backed by a hash table and provides constant-time performance (O(1)) for basic operations like add, remove, and contains, assuming a good distribution of hash values. Elements in a HashSet are unordered.
  • TreeSet: It is backed by a balanced binary search tree (a Red-Black tree) and provides logarithmic-time performance (O(log n)) for basic operations like add, remove, and contains. Elements in a TreeSet are sorted according to their natural order or by a custom comparator.

What is the difference between a Synchronized Collection and a Concurrent Collection?

For a given collection, you can get a synchronized collection backed by given collection from Collections utility class using methods like Collections.synchronizedList(), Collections.synchronizedSet(), etc. The user must manually synchronize over the returned collection while iterating over it and making any changes as the collection cannot be modified by multiple threads simultaneously. The utility class provides methods to get the thread-safe version of a map also.
Concurrent collections are those collections available as a part of java.util.concurrent package. These are designed to be thread-safe and allows multiple threads to access different parts of the collection at a given point of time. These collections, in contrast to their synchronized counterparts, do not use a common lock over the full collection. Instead, they are divided into sub-regions and each region is set with a separate lock. Multiple threads, can thus, access the collection but for a single region, only one thread can gain access at a particular time.

What is ConcurrentLinkedDeque?

It is a thread-safe implementation for a Deque. Similar to many other implementations under java.util.concurrent package, a ConcurrentLinkedDeque does not allow null inputs. Because they are asynchronous in nature, iterating values from the collection will not return correct values if at the same time another thread is modifying the collection. It implements all optional methods of Deque interface.

For a given TreeMap, how can we find out the position for a given entry?

Since you add elements to a TreeMap, the keys will be already sorted and ordered in the natural order. You can copy the keys to an array and use Arrays.binarySearch() to find the index of given key.

3 thoughts on “Java Collection Interview Questions and Answer”

  1. Good collection of collection framework. I am a self taught java professional looking for work. Please share more questions on Map interface and its implementation. It really helps to brush up the concepts

    Reply
    • I would definitely be writing more about the interview questions. But other topics have priority for me now. Happy that you like the post.

      Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.