Collections Framework forms the backbone of Java. Therefore, Java Collections interview questions hold immense importance for a career in Java.
According to Oracle’s Java documentation, Collections Framework is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details.
We have divided the Java Collections interview questions into five sections.
- What is the Collections Framework in Java and its advantages?
- Explain the Collections Framework hierarchy in Java.
- Name and explain various interfaces of the Collections framework.
- What is a List interface in Java? Name the classes which implement it.
- What is an ArrayList in Java?
- What is the difference between Array and ArrayList?
- How to reverse the list?
- What is a Set interface in Java and its various implementations?
- What are the differences between Set and Queue in Java?
- How HashSet Collection in Java store elements?
- What are the differences between HashSet and TreeSet?
- What is a LinkedHashSet in Set interface? Give an example.
- What is a Map interface in Java?
- What are the Collection views in Java by the Map interface?
- How will you design a good key for HashMap in Java?
- Explain the differences between HashMap and TreeMap.
- What is a Queue interface in Java? Explain its methods.
- What are the differences between Queue and Deque?
1. What is the Collections Framework in Java and its advantages?
The Collections framework is a set of classes and interfaces with defined architecture, where the algorithms or methods are already defined. Programmers just need to use them and there is no need to write code for any of them.
Hence collections framework consists of:
The advantages of Collections Framework in Java are:
- Better performance: The in-built algorithms, data structures, and methods are optimized for high-performance.
- Less effort: Reduces overall effort for writing, designing, implementing, and learning APIs. Because most of the methods across classes are similar, this reduces the effort.
- Reduced programming time: Since, the data structures, algorithms, and their methods are already written in Java, programmers’ time is reduced considerably.
- Reusability: Everyone can use the same set of standard collections and their algorithms which enhances reusability.
2. Explain the Collections Framework hierarchy in Java.
This is one of the basic questions from Java Collections interview questions. Knowledge of the framework hierarchy provides clarity of the interfaces and classes present in it.
Package java.util contains all the classes and interfaces of the collections framework.
Below is the collections framework hierarchy in Java where:
- Green box signifies an interface
- Orange box signifies a class which implements the interface above it.
The components of the hierarchy are:
1. Iterable interface
2. Collection Interface
- ArrayList class
- LinkedList class
- Vector class
- Stack class
3. Queue interface
- Priority queue
4. Set interface
- HashSet class
- LinkedHashSet class
5. Deque interface
- ArrayDeque class
6. SortedSet interface
- TreeSet class
7. Map interface
- HashTable class
- LinkedHashMap class
- HashMap class
- SortedMap interface : TreeMap class
3. Name and explain various interfaces of the Collections framework.
The core collection interfaces form the foundation of the collections framework.
- Collection: Collection interface is at the root of the hierarchy, providing access to the group of objects.
- List: List interface extends collection interface in Java. Its object stores an ordered collection of elements which need not be unique.
- Queue: Holds multiple elements before processing, usually it is treated FIFO(First-in, First-out).
- Dequeue: Holds multiple elements before processing like List. Dequeue can be FIFO or LIFO(Last-in, First-out). Insertion, removal, and retrieval of elements are from both ends.
- Set: Extends collection interface and contains unique elements.
- SortedSet: Extends set interface and stores unique elements in sorted order.
- Map: Object of Map interface maps the keys to values.
- SortedMap: A map that stores mapping in ascending order of keys. E.g. dictionary.
1. What is a List interface in Java? Name the classes which implement it.
- The List is a child interface of the Collection interface in Java.
- It stores the elements in order(sequence).
- Duplicate elements are allowed.
- The List is an interface hence we cannot create objects of this. We can use a class that extends List and then create an object of that class.
- Operations performed on List interface in Java are- creation, positional access, search, iteration, etc.
Classes which extend List interface in Java are:
2. What is an ArrayList in Java?
ArrayList is a class in the java.util package. The built-in array of Java has a fixed size while ArrayList is a dynamic array. Below is the syntax to create a new ArrayList in Java:
Methods available in ArrayList are:
- 2 2
More about ArrayListhere.
3. What is the difference between Array and ArrayList?
|We cannot change the size of an Array after creation. It is static.||ArrayList is dynamic and its size can be modified later.|
|An Array is a built-in data structure by Java.||It is a class provided in the Collections Framework.|
|Accessed by square brackets ‘’.||Accessed by methods provided by Collections Framework.|
|Supports both primitive data types and objects of classes.||The primitive data types are not supported.|
Primitive data types are stored in contiguous locations.
In the case of an array of objects, the reference to objects is stored in contiguous memory locations. However, the objects themselves will be scattered in memory.
|There are no primitive data types. Hence, the reference to objects is stored in contiguous memory locations like arrays.|
|Does not have methods like remove(), indexOf(), add() etc.||Has more supportive methods like remove(), indexOf(), add() etc.|
|We use for/for each loop to iterate over the array.||We use an iterator to iterate over the ArrayList.|
|Arrays can be multi-dimensional.||ArrayList can be single-dimensional containing objects.|
|Elements are added by assignment(=) operator.||Objects are assigned using the add() method.|
4. How to reverse the list?
1. We can use java.util.Collections.reverse() method to reverse an ArrayList.
2. To reverse a LinkedList same code can be used just replace ArrayList definition with ‘List mylist = new LinkedList();’
3. Array does not have a reverse() method. We can use the same reverse method to reverse an Array.
1. What is a Set interface in Java and its various implementations?
- The Set interface extends the Collection interface and provides an implementation of a mathematical set.
- A set cannot contain duplicate elements.
- The elements in a set are not ordered.
- Since it extends the Collection interface, the Set interface has methods inherited from the Collection interface.
- One additional method is to disallow the insertion of duplicate elements.
- Set is an interface hence we can not create objects of it. We need to use the classes which implement the set interface.
The various implementations of Set interface in Java are:
Example to demonstrate Set declaration and usage:
2. What are the differences between Set and Queue in Java?
|Set is not ordered.||A Queue is ordered.|
|Do not contain duplicates.||Can contain duplicates.|
|Do not maintain FIFO order.||Maintains First-in, First-out(FIFO) order|
|We can store a maximum of one NULL element.||Queue implementations do not allow NULL value elements except LinkedList.|
|Implementations are EnumSet, HashSet, LinkedHashSet, TreeSet.||Implementations are LinkedList, PriorityQueue.|
3. How HashSet Collection in Java store elements?
HashSet is backed up by HashMap to store its elements. Whenever we create a HashSet object, one corresponding HashMap object also gets created. Hence, the elements which we enter into HashSet are actually entered into HashMap objects. Wherein the value of the key is stored as a constant - ’PRESENT’.
Whenever a HashSet constructor is used in the code, the constructor internally creates a HashMap object.
Below is an example and pictorial depiction of how HashSet stores the elements.
Diagram below shows how a single add() method of HashSet creates a new HashMap object internally. It shows the contents of an internal HashMap object which has ‘Key’ and ‘Value’ pairs.
4. What are the differences between HashSet and TreeSet?
|Stores elements in an unordered set.||Stores elements in order.|
|Can store NULL values.||Does not allow NULL values.|
|Takes a constant time for operations- add, remove, etc.||Takes log(n) time for operations - add, remove etc.|
|Internally, HashSet is backed up by HashMap.||Internally, TreeSet is backed up by Navigable TreeMap.|
|HashSet is faster in performance compared to TreeSet. Because it provides a constant-time execution performance for operations like add, remove, contains, etc.||TreeSet is slower than HashSet in performance time. It provides log(n) time-cost in the execution of operations.|
|Does not have methods like ceiling(), lower(), first(), last() etc.||Has more capable methods like ceiling(), lower(), first(), last() etc.|
- LinkedHashSet inherits HashSet and extends Set interface.
- Like HashSet its elements are unique.
- It may contain NULL elements.
- LinkedHashSet maintains a linked list and preserves the order of element insertion.
- While traversing the LinkedHashSet the elements are returned in the order they were inserted.
Below is the code snippet for creating a LinkedHashSet object.
1. What is a Map interface in Java?
The Map interface is present in the java.util package and is not related to the Collection interface. Hence, its behaviour is different from the Collection interface.
An object of the Map interface stores a key-value pair called entry. The key value is unique and is useful in searching, deleting, and updating an element. The value can be a duplicate.
Operations on Map interface:
- Basic operations - put, get, remove, containsKey, containsValue, size, and empty
- Bulk operations - putAll and clear
- Collection View operations - keySet, entrySet, and values
More on Map interface here.
Below is the Map interface hierarchy diagram:
2. What are the Collection views in Java by the Map interface?
Although the Map interface is a part of the Collections Framework, it is different from the collection interface. Therefore, it provides Collection views to view the Map object’s elements in the form of Collection.
There are three methods for this purpose:
- keySet() - Returns a Set view of keys present in the Map.
- values() - Returns a Collection view of values present in the Map.
- values()- Returns a Collection view of values present in the Map.
3. How will you design a good key for HashMap in Java?
HashMap object stores a key-value pair. Key is processed by a hash function to provide a hash code. This hash-code acts as an index to the buckets or locations where the actual value is stored.
During lookup, the key is hashed and the resulting hash shows the location where the actual value is stored.
This is depicted in the diagram below:
The key-value pairs are stored in the memory with hashing. And then if we change the key, the hash-code will change for lookup. Therefore, the new hash-code will not match the actual hash-code and the value will be lost. Hence, we should use a key that is immutable e.g. String class. Because the objects of the String class cannot be changed once created. Therefore, they are the best candidate for the key.
4. Explain the differences between HashMap and TreeMap.
|HashMap is based on a hashtable.||TreeMap is based on tree-structure.|
|Sorting of keys not available.||Sorting of keys can be performed.|
|Faster in performance.||Slower in performance.|
|A single NULL key is permitted.||NULL key not permitted.|
|Storage is unordered.||Storage of elements is ordered.|
|Uses equals() method to compare keys.||Uses compareTo() method to compare keys.|
|Performs basic functions like put(), get(), keySet() etc.||Performs higher functionalities by firstKey(), lastKey(), tailMap() etc.|
1. What is a Queue interface in Java? Explain its methods.
Queue interface provides an implementation of the Queue data structure. It extends the Collection interface. The Queue is an interface so we cannot directly create objects of it.
Therefore, there are three classes of Queue interface in Java:
Methods of Queue interface are:
- add(): Inserts element into the queue at the tail.
- peek(): Retrieves the element at the head of the queue. Returns NULL if empty queue.
- remove(): Removes the element at the head of the queue.
- element(): Checks if there are elements in the queue. Throws an exception if the queue is empty.poll(): Returns and removes the head of the queue.
- size(): Returns the number of elements in the queue.
2. What are the differences between Queue and Deque?
|In Queue, we insert elements in one end and remove them from another end.||Deque is a ‘double-ended queue’. Where insertion and removal can be from both ends.|
|Cannot be used for stack implementation.||Can be used for both- queue and stack implementation.|
|Extends Collection interface.||Extends Queue interface.|
Other Backend Technology Interview Questions and Answers
C Programming Language Interview Questions | PHP Interview Questions | .NET Core Interview Questions | NumPy Interview Questions | API Interview Questions | FastAPI Python Web Framework | Java Exception Handling Interview Questions | OOPs Concepts in Java Interview Questions | System Design Interview Questions | Data Structure Concepts | Node.js Interview Questions | Django Interview Questions | React Interview Questions | Microservices Interview Questions | Key Backend Development Skills | Data Science Interview Questions | Python Interview Questions | Java Spring Framework Interview Questions