Here is a list of commonly asked Java Collection Framework interview questions, along with detailed explanations:
1. What is the Java Collection Framework?
The Java Collection Framework provides a set of interfaces, classes, and algorithms to store and manipulate data. It includes interfaces like List, Set, Queue, and Map and their implementations like ArrayList, HashSet, PriorityQueue, and HashMap.
2. Difference Between List, Set, and Map
Key Differences:
Aspect |
List |
Set |
Map |
Duplicates |
Allows duplicates |
No duplicates |
Keys: No duplicates |
Order |
Maintains insertion order |
Some maintain order |
No guaranteed order |
Examples |
ArrayList , LinkedList |
HashSet , TreeSet |
HashMap , TreeMap |
3. How does HashMap
work internally?
Explanation:
HashMap
Uses an array and linked list (or a tree since Java 8) for storing entries.
- Key Steps:
- The key's
hashCode()
determine the bucket index.
- If a collision occurs (same hash index), entries are stored in a linked list or tree.
- Improvements in Java 8:
- If the linked list size exceeds 8, it converts to a balanced tree for better performance.
- Rehashing:
- When the
HashMap
exceeds the load factor (default 0.75), the array size doubles.
4. What is the difference between HashMap
and TreeMap
?
Key Differences:
Aspect |
HashMap |
TreeMap |
Ordering |
No order guarantee |
Sorted by the natural order |
Performance |
O(1) for operations |
O(log n) for operations |
Null Keys |
Allows one null key |
Does not allow null keys |
5. How does ConcurrentHashMap
achieve thread-safety?
Explanation:
- Locking Mechanism:
- Instead of locking the entire map,
ConcurrentHashMap
uses bucket-level locking (16 segments by default).
- No Null Values/Keys:
- To avoid ambiguity during concurrency,
null
keys or values are not allowed.
- Performance:
- Allows multiple threads to operate on different buckets simultaneously.
6. How is ArrayList
different from LinkedList
?
Key Differences:
Aspect |
ArrayList |
LinkedList |
Data Structure |
Dynamic Array |
Doubly Linked List |
Access Time |
O(1) for get |
O(n) for get |
Insertion/Deletion |
Slow (shifting required) |
Fast at head or tail |
Memory |
Less overhead |
More memory overhead |
7. What is the difference between Iterator
and ListIterator
?
Explanation:
Aspect |
Iterator |
ListIterator |
Direction |
One-way (forward) |
Two-way (forward/backward) |
Available Methods |
hasNext() , next() , remove() |
Adds hasPrevious() , previous() |
Applicable To |
All collections |
Only List |
8. What are fail-fast and fail-safe iterators?
Explanation:
- Fail-Fast Iterators:
- Throw
ConcurrentModificationException
if the collection is structurally modified during iteration.
- Example: Iterators of
ArrayList
, HashMap
.
- Fail-Safe Iterators:
- Operate on a copy of the collection so structural modifications do not affect them.
- Example: Iterators of
CopyOnWriteArrayList
, ConcurrentHashMap
.
9. How can you remove duplicates from a List
?
Example:
import java.util.*;
public class RemoveDuplicates {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 2, 3, 4, 4, 5);
Set<Integer> set = new HashSet<>(list);
System.out.println("List without duplicates: " + new ArrayList<>(set));
}
}
10. What is the difference between HashSet
and TreeSet
?
Key Differences:
Aspect |
HashSet |
TreeSet |
Ordering |
No order guarantee |
Sorted by natural order |
Performance |
O(1) for add/remove |
O(log n) for add/remove |
Null Values |
Allows one null value |
Does not allow null |
11. What is the difference between synchronizedList
and CopyOnWriteArrayList
?
Aspect |
SynchronizedList |
CopyOnWriteArrayList |
Locking |
Locks entire list |
Creates a copy of the list |
Performance |
Slower during reads |
Faster during reads |
Thread Safety |
Requires manual synchronization |
Automatic thread safety |
12. How to sort a List
?
Example:
import java.util.*;
public class SortListExample {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(5, 2, 8, 1, 3);
Collections.sort(list);
System.out.println("Sorted List: " + list);
}
}
13. How to find the frequency of elements in a List
?
Example:
import java.util.*;
public class FrequencyExample {
public static void main(String[] args) {
List<String> list = Arrays.asList("A", "B", "A", "C", "B", "A");
Map<String, Integer> frequencyMap = new HashMap<>();
for (String s : list) {
frequencyMap.put(s, frequencyMap.getOrDefault(s, 0) + 1);
}
System.out.println("Frequencies: " + frequencyMap);
}
}
14. What is the difference between Queue
and Deque
?
Key Differences:
Aspect |
Queue |
Deque |
Direction |
FIFO (First In, First Out) |
Both ends (FIFO/LIFO) |
Methods |
add() , remove() |
Adds offerFirst() , offerLast() |
15. When to use Collections.synchronizedList
vs CopyOnWriteArrayList
?
Key Considerations:
- Use
Collections.synchronizedList
:
- If there are frequent write operations.
- Requires external synchronization for iteration.
- Use
CopyOnWriteArrayList
:
- If there are more read operations than writes.
- Provides thread-safe iteration without manual synchronization.
Pro Tips for Interviews:
- Understand Internal Working:
- Be prepared to explain how
HashMap
, HashSet
, and ArrayList
work internally.
- Big-O Complexity:
- Know the time complexities of key operations (add, remove, get).
- Thread Safety:
- Understand thread-safe alternatives like
ConcurrentHashMap
, CopyOnWriteArrayList
.
- Custom Implementations:
- Be ready to write custom implementations of a collection (e.g., a custom linked list or stack).
Let me know if you need any examples or deeper explanations! 😊