In this article, we will cover frequently asked Java Collections Interview Questions. We have categorized the questions into two parts
- Basic Java Collections Interview Questions
- Advanced Level Java Collections Interview Questions
Basic Java Collections Interview Questions
In this section, we will cover various basic Java Collections Interview Questions.
What is Collections Framework Hierarchy ?
Please read Collections Framework – High Level View
Working of ArrayList? How does an ArrayList Grow?
Please read All About ArrayList
Array vs ArrayList
This is one of the most frequently asked Java Collections Interview Questions.
Please read Array vs ArrayList for in-depth understanding of the differences.
ArrayList vs Vector
Please read ArrayList vs Vector
ArrayList vs LinkedList
Please read ArrayList vs LinkedList
Working of HashMap? Explain Internal Working of HashMap
This is most popular Java Collections Interview Questions.
Please read HashMap for in-depth understanding of the HashMap.
HashMap vs Hashtable vs SynchronizedHashMap vs ConcurrentHashMap
Please read HashMap vs Hashtable vs SynchronizedHashMap vs ConcurrentHashMap
What is LinkedHashMap ?
Please read LinkedHashMap
What is TreeMap ?
Please read TreeMap
Comparable vs Comparator
Please read Comparable vs Comparator
CopyOnWriteArrayList vs SynchronizedList
Please read CopyOnWriteArrayList vs SynchronizedList
fail-fast iterator Vs fail-safe iterator
Please read fail-fast iterator Vs fail-safe iterator
Why Generics was Introduced in Java 5?
Please read Why Generics was Introduced in Java 5?
What is Type Erasure?
Please read Generics: Type Erasure
Advanced Level Java Collections Interview Questions
In this section, we will cover various advanced level Java Collections Interview Questions.
Synchronized Collections vs. Concurrent Collections
Please read Synchronized Collections vs. Concurrent Collections
What is a PriorityQueue ?
Please read PriorityQueue
Explain the purpose of the IdentityHashMap in Java.
The purpose of the IdentityHashMap in Java is to compare keys based on their reference equality rather than using the equals()
method. This means that two keys are considered equal only if they refer to the same object in memory. It is useful in scenarios where object identity is more important than the equality defined by the equals()
method.
Here’s a code example that demonstrates the usage of IdentityHashMap:
import java.util.IdentityHashMap;
public class IdentityHashMapExample {
public static void main(String[] args) {
// Create an IdentityHashMap
IdentityHashMap<String, Integer> identityMap = new IdentityHashMap<>();
// Create two different String objects with the same content
String key1 = new String("John");
String key2 = new String("John");
// Put key-value pairs into the IdentityHashMap
identityMap.put(key1, 25);
identityMap.put(key2, 30);
// Size of the IdentityHashMap will be 2 because key1 and key2 are different objects
System.out.println("Size of IdentityHashMap: " + identityMap.size());
// Get the value associated with key1
int value1 = identityMap.get(key1);
System.out.println("Value for key1: " + value1);
// Get the value associated with key2
int value2 = identityMap.get(key2);
System.out.println("Value for key2: " + value2);
// Remove key1 from the IdentityHashMap
identityMap.remove(key1);
// Size of the IdentityHashMap will be 1 after removal
System.out.println("Size of IdentityHashMap after removal: " + identityMap.size());
}
}
In this example, we create an IdentityHashMap
and put two different String
objects (key1
and key2
) as keys, even though they have the same content. The size of the IdentityHashMap
will be 2 because it considers them as distinct keys due to their different object references. We retrieve the values associated with key1
and key2
, and then remove key1
from the IdentityHashMap
. The size of the IdentityHashMap
becomes 1 after the removal.
What is the purpose of the WeakHashMap in Java?
The purpose of the WeakHashMap in Java is to provide a map implementation that uses weak references for its keys. This means that if a key is no longer strongly referenced elsewhere in the program, it becomes eligible for garbage collection, allowing the corresponding entry in the WeakHashMap to be automatically removed.
Here’s a code example that demonstrates the usage of WeakHashMap:
import java.util.Map;
import java.util.WeakHashMap;
public class WeakHashMapExample {
public static void main(String[] args) {
// Create a WeakHashMap
Map<Key, String> weakHashMap = new WeakHashMap<>();
// Create two Key objects
Key key1 = new Key("key1");
Key key2 = new Key("key2");
// Put key-value pairs into the WeakHashMap
weakHashMap.put(key1, "Value 1");
weakHashMap.put(key2, "Value 2");
// Size of the WeakHashMap will be 2
System.out.println("Size of WeakHashMap: " + weakHashMap.size());
// Set the Key references to null
key1 = null;
key2 = null;
// Perform garbage collection
System.gc();
// Wait for a moment to allow the garbage collector to remove the weakly referenced keys
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Size of the WeakHashMap will be 0 as the weakly referenced keys have been removed
System.out.println("Size of WeakHashMap after garbage collection: " + weakHashMap.size());
}
static class Key {
private String name;
public Key(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
}
In this example, we create a WeakHashMap
and put two Key
objects (key1
and key2
) as keys. The Key
class is a custom class that overrides the toString()
method to provide a meaningful string representation. After putting the key-value pairs, we set key1
and key2
references to null
.
We then invoke the garbage collector using System.gc()
and wait for a moment to allow the garbage collector to remove the weakly referenced keys. Finally, we print the size of the WeakHashMap
and observe that it becomes 0 as the weakly referenced keys have been removed.
How does the EnumMap work in Java?
EnumMap is a specialized implementation of the Map interface designed for use with enum keys. It is internally represented as an array and provides efficient and type-safe storage for enum constants. EnumMap guarantees that the iteration order matches the natural order of the keys, which is the order in which enum constants are declared.
Here’s a code example that demonstrates the usage of EnumMap:
import java.util.EnumMap;
import java.util.Map;
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class EnumMapExample {
public static void main(String[] args) {
// Create an EnumMap with Day enum as the key and String as the value
EnumMap<Day, String> tasks = new EnumMap<>(Day.class);
// Put key-value pairs into the EnumMap
tasks.put(Day.MONDAY, "Do laundry");
tasks.put(Day.TUESDAY, "Go grocery shopping");
tasks.put(Day.WEDNESDAY, "Attend a meeting");
// Get the value associated with a specific key
String task = tasks.get(Day.TUESDAY);
System.out.println("Task for Tuesday: " + task);
// Iterate over the EnumMap
for (Map.Entry<Day, String> entry : tasks.entrySet()) {
Day day = entry.getKey();
String taskDescription = entry.getValue();
System.out.println(day + ": " + taskDescription);
}
// Size of the EnumMap
System.out.println("Size of EnumMap: " + tasks.size());
// Remove a key-value pair from the EnumMap
tasks.remove(Day.MONDAY);
// Check if the EnumMap contains a specific key
boolean containsKey = tasks.containsKey(Day.MONDAY);
System.out.println("Contains key 'MONDAY'? " + containsKey);
// Clear all key-value pairs from the EnumMap
tasks.clear();
// Check if the EnumMap is empty
boolean isEmpty = tasks.isEmpty();
System.out.println("Is EnumMap empty? " + isEmpty);
}
}
In this example, we create an EnumMap
with the Day
enum as the key and String
as the value. We put key-value pairs into the EnumMap
using enum constants as keys. We retrieve the value associated with a specific key, iterate over the EnumMap
, and print the key-value pairs. We also demonstrate getting the size of the EnumMap
, removing a key-value pair, checking if the EnumMap
contains a specific key, and clearing all key-value pairs from the EnumMap
. Finally, we check if the EnumMap
is empty.
What is the purpose of the Deque interface in Java?
The Deque (Double Ended Queue) interface extends the Queue interface and allows elements to be added or removed from both ends. It supports operations such as inserting, removing, and retrieving elements from both the head and the tail of the queue. An example implementation is ArrayDeque, which provides efficient operations for both stack-like and queue-like behavior.
import java.util.ArrayDeque;
import java.util.Deque;
public class DequeExample {
public static void main(String[] args) {
Deque<String> deque = new ArrayDeque<>();
// Add elements to the head of the deque
deque.addFirst("One");
deque.addFirst("Two");
deque.addFirst("Three");
// Add elements to the tail of the deque
deque.addLast("Four");
deque.addLast("Five");
// Print the deque in order
System.out.println("Deque: " + deque);
// Remove elements from the head and tail of the deque
String firstElement = deque.removeFirst();
String lastElement = deque.removeLast();
// Print the removed elements
System.out.println("Removed first element: " + firstElement);
System.out.println("Removed last element: " + lastElement);
// Print the deque after removal
System.out.println("Updated deque: " + deque);
}
}
Deque: [Three, Two, One, Four, Five]
Removed first element: Three
Removed last element: Five
Updated deque: [Two, One, Four]
What is the purpose of the NavigableMap interface in Java?
The NavigableMap interface extends the SortedMap interface and provides methods for navigation based on the keys. It supports operations such as finding the closest key, retrieving submaps, and performing higher/lower key lookups. An example implementation is TreeMap
, which maintains the keys in sorted order and allows efficient operations based on key navigation.
import java.util.NavigableMap;
import java.util.TreeMap;
public class NavigableMapExample {
public static void main(String[] args) {
NavigableMap<Integer, String> navigableMap = new TreeMap<>();
navigableMap.put(1, "One");
navigableMap.put(2, "Two");
navigableMap.put(3, "Three");
navigableMap.put(4, "Four");
navigableMap.put(5, "Five");
// Get the closest key less than or equal to a given key
int floorKey = navigableMap.floorKey(3);
System.out.println("Floor key of 3: " + floorKey);
// Get the closest key greater than or equal to a given key
int ceilingKey = navigableMap.ceilingKey(3);
System.out.println("Ceiling key of 3: " + ceilingKey);
// Get a submap of keys within a range
NavigableMap<Integer, String> subMap = navigableMap.subMap(2, true, 4, true);
System.out.println("Submap: " + subMap);
}
}
Floor key of 3: 3
Ceiling key of 3: 3
Submap: {2=Two, 3=Three, 4=Four}
Conclusion
This article “Java Collections Interview Questions” aims to provide a comprehensive resource for Java developers preparing for interviews or seeking a deeper understanding of collections.
We hope that “Java Collections Interview Questions” proves to be a beneficial guide, assisting developers in strengthening their grasp of collections and enabling them to excel in interviews.