Collections Interview Questions
Deep dive into 40 Java Collections Framework interview questions covering List, Set, Map, Queue, sorting, internal workings, and concurrent collections.
Deep dive into 40 Java Collections Framework interview questions covering List, Set, Map, Queue, sorting, internal workings, and concurrent collections. This interview-focused guide covers essential collections interview questions concepts for technical interviews.
Collections Interview Questions
The Java Collections Framework is the most heavily tested topic in Java interviews. These 40 questions cover internal implementations, comparison scenarios, thread-safe alternatives, and the Java 8 improvements every developer should know.
1. How does HashMap work internally?
- Uses an array of Node (buckets).
put(key, value):- Calculates
hash(key). - Finds index:
hash % capacity. - If empty, inserts node.
- If collision, uses LinkedList (or Red-Black Tree in Java 8+ if node count > 8).
- Calculates
get(key):- Calculates hash.
- Finds bucket.
- Traverses list/tree comparing keys using
.equals().
2. ArrayList vs LinkedList?
| Feature | ArrayList | LinkedList |
|---|---|---|
| Structure | Dynamic Array | Doubly Linked List |
| Access (get) | O(1) - Fast | O(n) - Slow |
| Insert/Delete | O(n) - Slow (shifting) | O(1) - Fast (pointer change) |
| Usage | Read-heavy | Write-heavy |
3. Difference between HashMap, LinkedHashMap, and TreeMap?
- HashMap: No order. Fastest O(1).
- LinkedHashMap: Insertion order. O(1).
- TreeMap: Sorted order (natural or Comparator). O(log n).
4. What are Fail-Fast iterators?
- Immediately throw
ConcurrentModificationExceptionif collection is modified during iteration. - Examples:
ArrayList,HashSet,HashMap.
5. What are Fail-Safe iterators?
- Traverse a clone or snapshot. No Exception.
- Examples:
CopyOnWriteArrayList,ConcurrentHashMap.
6. Contract between hashCode() and equals()?
- If
equals()is true,hashCode()MUST be same. - If
hashCode()is same,equals()implied? NO (Collision). - Always override both together.
7. What is the difference between Collection and Collections?
- Collection: Root interface of the Collections Framework. Sub-interfaces: List, Set, Queue.
- Collections: Utility class with static methods for sorting, searching, synchronizing collections (
sort(),reverse(),synchronizedList(),unmodifiableList()).
8. What is the difference between List, Set, and Map?
- List: Ordered collection. Allows duplicates. Access by index. (ArrayList, LinkedList, Vector)
- Set: No duplicates. Unordered (HashSet) or sorted (TreeSet). No index-based access.
- Map: Key-value pairs. Keys must be unique. Values can be duplicated. (HashMap, TreeMap, LinkedHashMap)
[!NOTE] Map is NOT a sub-interface of Collection. It's a separate hierarchy in the Collections Framework.
9. What is the difference between HashSet and TreeSet?
| Feature | HashSet | TreeSet | |---------|---------|---------| | Order | No order | Sorted (natural/Comparator) | | Performance | O(1) | O(log n) | | Null | Allows one null | No null (NullPointerException) | | Backed by | HashMap | TreeMap (Red-Black Tree) | | When to use | Fast lookup | Sorted data needed |
10. What is the difference between HashMap and Hashtable?
| Feature | HashMap | Hashtable | |---------|---------|-----------| | Synchronized | No | Yes (thread-safe) | | Null keys | 1 null key allowed | No null keys | | Null values | Allowed | No null values | | Performance | Faster | Slower | | Legacy | Java 1.2 | Java 1.0 (legacy) | | Iterator | Fail-fast | Fail-fast (Enumerator: not) |
[!TIP] Use
ConcurrentHashMapinstead ofHashtablefor thread-safe maps in modern Java. It has better performance through segment-level locking.
11. What is Vector and how does it differ from ArrayList?
- Vector: Legacy class (Java 1.0). Synchronized (thread-safe). Slower due to synchronization overhead.
- ArrayList: Introduced in Java 1.2. Not synchronized (not thread-safe). Faster.
- Both are resizable arrays. For thread-safe List, use
CopyOnWriteArrayListorCollections.synchronizedList().
12. What is the difference between Comparable and Comparator?
| Feature | Comparable | Comparator | |---------|-----------|------------| | Package | java.lang | java.util | | Method | compareTo() | compare() | | Objects | 1 object | 2 objects | | Natural ordering | Defines natural order | External ordering | | Modification | Modifies original class | Separate class | | Usage | Collections.sort(list) | Collections.sort(list, comparator) |
13. What is the difference between Queue and Deque?
- Queue: FIFO (First In First Out). Operations: add/offer (end), remove/poll (front), peek (front).
- Deque: Double-ended queue. Insert/remove from both ends. Can be used as Stack or Queue.
14. What is PriorityQueue?
A PriorityQueue orders elements based on their natural order or a custom comparator. The head contains the smallest element. It doesn't allow null elements. Uses a binary heap internally. O(log n) for add/remove, O(1) for peek.
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(5); pq.add(1); pq.add(3);
System.out.println(pq.poll()); // 1 (smallest first)
15. What happens if HashMap capacity exceeds load factor?
When entries exceed load factor × capacity, HashMap resizes (doubles capacity) and rehashes all entries. Default load factor: 0.75. Default initial capacity: 16. Rehashing is expensive — set initial capacity appropriately.
16. What is TREEIFY_THRESHOLD in HashMap?
Java 8+ threshold (value: 8). When a bucket's LinkedList grows beyond 8 nodes, it's converted to a Red-Black Tree for better performance (O(log n) vs O(n)). UNTREEIFY_THRESHOLD (value: 6) converts back to list when shrinking.
17. What is the difference between synchronized collections and concurrent collections?
- Synchronized (
Collections.synchronizedList): Locks entire collection. Only one thread can access at a time. Poor performance under contention. - Concurrent (
ConcurrentHashMap,CopyOnWriteArrayList): Uses segment/partition-level locking. Multiple threads can read/write concurrently. Better scalability.
18. How does ConcurrentHashMap work internally?
Uses bucket-level locking (not full table lock). Divides map into segments (Java 7) or uses CAS + synchronized per bucket (Java 8+). Multiple threads can write to different buckets simultaneously. Reads are mostly lock-free.
19. What is CopyOnWriteArrayList?
Thread-safe variant of ArrayList. Every write operation (add, set, remove) creates a fresh copy of the underlying array. Iterators work on a snapshot. Expensive for writes, ideal for read-heavy scenarios.
20. What is the default size and resizing of ArrayList?
Default initial capacity: 10. When full, grows by 50% (new capacity = old + old/2). ensureCapacity() can pre-allocate space to avoid repeated resizing.
21. What is a WeakHashMap?
A WeakHashMap holds weak references to keys. When the key object has no strong references, the entry is eligible for garbage collection. Useful for metadata caching or listener management.
22. What is an IdentityHashMap?
IdentityHashMap uses reference equality (==) instead of object equality (equals()) for comparing keys. Rarely used. Useful for topology preserving object graphs or serialization frameworks.
23. What is an EnumSet?
A specialized Set for enum types. Extremely fast and memory efficient (uses bit vector internally). Elements must be from a single enum type.
enum Day { MON, TUE, WED, THU, FRI }
EnumSet<Day> weekdays = EnumSet.range(Day.MON, Day.FRI);
24. What is BlockingQueue?
A thread-safe queue that supports blocking operations: waits for space before insertion, waits for elements before removal. Used in Producer-Consumer patterns.
Implementations: ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue.
25. What are ArrayBlockingQueue vs LinkedBlockingQueue?
- ArrayBlockingQueue: Bounded capacity. Single lock. Fixed-size array. Must specify capacity.
- LinkedBlockingQueue: Optionally bounded. Separate locks for head and tail. Better concurrency. Default:
Integer.MAX_VALUE.
26. What is the difference between poll(), remove(), and peek() in Queue?
| Method | Empty Queue |
|--------|-------------|
| add() | Throws exception |
| offer() | Returns false |
| remove() | Throws exception |
| poll() | Returns null |
| element() | Throws exception |
| peek() | Returns null |
27. How to make a collection read-only?
Use Collections utility methods: unmodifiableList(), unmodifiableSet(), unmodifiableMap(). Any modification attempt throws UnsupportedOperationException.
List<String> readOnly = Collections.unmodifiableList(list);
28. How to make a collection thread-safe?
Collections.synchronizedList(),synchronizedMap(),synchronizedSet()(synchronized wrappers)ConcurrentHashMap,CopyOnWriteArrayList,ConcurrentLinkedQueue(concurrent collections)Vector,Hashtable(legacy, avoid)
29. What are Generics in Collections?
Generics provide compile-time type safety. Prevent ClassCastException at runtime. Denoted by angle brackets: List<String>. Unchecked warnings appear without generics.
List<String> list = new ArrayList<>(); // Type-safe
list.add("Hello");
// list.add(42); // Compile error!
30. What is Type Erasure?
Java generics use type erasure: generic type information is removed at compile time. List<String> and List<Integer> become just List at runtime. This ensures backward compatibility with pre-generics Java.
31. How does HashSet guarantee uniqueness?
HashSet is backed by a HashMap. Elements are stored as keys in the HashMap with a dummy value (PRESENT). The add operation uses map.put(e, PRESENT). Duplicate checks use hashCode() then equals().
32. What is the difference between Iterator and ListIterator?
| Feature | Iterator | ListIterator | |---------|----------|--------------| | Applicable to | All collections | List only | | Direction | Forward only | Forward + backward | | Add/Set/Remove | Remove only | Add, set, remove | | Index | No | Yes (nextIndex, previousIndex) | | Cursor | Single | Bidirectional |
33. What is LinkedHashMap access order?
LinkedHashMap can use access-order (not just insertion-order) via constructor: LinkedHashMap(int, float, boolean accessOrder). In access-order, the most recently accessed entry moves to the end. Foundation of LRU cache.
34. How to remove duplicates from an ArrayList?
- Convert to
LinkedHashSet(preserves order):new ArrayList<>(new LinkedHashSet<>(list)) - Use Java 8 Streams:
list.stream().distinct().collect(Collectors.toList()) - Manual loop with
contains()check (slow for large lists)
35. What is the difference between shallow copy and deep copy?
- Shallow copy: Copies references. Both lists point to same objects.
clone(),new ArrayList<>(original). - Deep copy: Copies objects themselves. Changes in copy don't affect original. Need custom implementation.
36. What are performance considerations for choosing collections?
- Random access: ArrayList (O(1)) over LinkedList (O(n))
- Searching sorted data: TreeSet (O(log n)) over HashSet (no order)
- Frequent inserts/deletes at ends: LinkedList
- Frequent inserts at specific index: ArrayList (shifting overhead)
- Thread safety: ConcurrentHashMap over Hashtable
- Memory: HashSet uses HashMap (overhead), TreeSet is lighter
37. How does stream() work with collections?
Stream API (Java 8+) provides functional operations: filter(), map(), sorted(), collect(), reduce(). Streams are lazy: intermediate operations don't execute until terminal operation.
List<String> filtered = list.stream()
.filter(s -> s.startsWith("A"))
.map(String::toUpperCase)
.collect(Collectors.toList());
38. What is the difference between forEach() and forEachOrdered() in streams?
- forEach(): No guarantee of order in parallel streams. Better performance.
- forEachOrdered(): Maintains encounter order even in parallel streams.
39. What is Collectors.toMap() and how to handle duplicate keys?
Collectors.toMap() converts a stream to a Map. Requires key and value mappers. Third argument resolves duplicate key conflicts.
Map<Long, String> map = users.stream()
.collect(Collectors.toMap(
User::getId,
User::getName,
(existing, replacement) -> replacement // merge function
));
40. What are the thread-safe alternatives for common collections?
| Collection | Thread-Safe Alternative | |------------|------------------------| | ArrayList | CopyOnWriteArrayList | | LinkedList | ConcurrentLinkedDeque | | HashSet | ConcurrentHashMap.newKeySet() / CopyOnWriteArraySet | | TreeSet | ConcurrentSkipListSet | | HashMap | ConcurrentHashMap | | TreeMap | ConcurrentSkipListMap | | Queue | ConcurrentLinkedQueue / BlockingQueue variants |
AI Mentor
Confused about "Java Collections interview questions and internal workings including HashMap, List, Set, Map, Queue, concurrent collections, and Java 8+ features"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 3What is the time complexity of get() in HashMap?