Java Collections and Generics Interview Questions and Answers
15 questions on List, Set, Map, HashMap internals, Comparable, fail-fast iterators, generics, and wildcards.
1. What are the main interfaces in the Java Collections Framework?
Collection is the root for List (ordered, allows duplicates), Set (no duplicates), and Queue/Deque (ordering for processing). Map is separate and stores key-value pairs. Common implementations are ArrayList, LinkedList, HashSet, LinkedHashSet, TreeSet, HashMap, LinkedHashMap, TreeMap, and ArrayDeque.
2. What is the difference between ArrayList and LinkedList?
ArrayList is backed by an array: random access by index is O(1), appending is amortized O(1), and inserting or removing in the middle is O(n) because elements shift. LinkedList is a doubly linked list: inserting or removing at a known node is O(1), but access by index is O(n), and each element costs extra memory. In practice ArrayList is the better default.
3. How does HashMap work internally?
It stores entries in an array of buckets. The key's hashCode picks the bucket, and equals() finds the right key inside it. Collisions are chained in a linked list, which is converted to a balanced tree when a bucket gets long (8 entries and the table has at least 64 buckets), keeping worst-case lookups at O(log n). When the number of entries passes capacity times the load factor (0.75 by default) the table doubles and entries are redistributed.
4. What happens if you use a mutable object as a HashMap key?
If a field used by hashCode or equals changes after the key is inserted, the entry sits in the wrong bucket and get() will no longer find it. Use immutable keys such as String, Integer, or records.
5. What is the difference between HashMap, Hashtable, and ConcurrentHashMap?
HashMap is not thread safe and allows one null key and null values. Hashtable is a legacy class with every method synchronized, and it forbids nulls. ConcurrentHashMap is designed for concurrency, uses fine-grained locking and compare-and-swap, forbids nulls, and offers atomic operations such as computeIfAbsent and merge. Prefer ConcurrentHashMap when multiple threads share a map.
6. How does HashSet ensure uniqueness?
A HashSet is backed by a HashMap: elements are stored as keys with a constant dummy value. add() returns false when an equal element (by hashCode and equals) is already present.
7. What is the difference between HashMap, LinkedHashMap, and TreeMap?
HashMap has no ordering guarantee and offers O(1) average operations. LinkedHashMap keeps insertion order (or access order). TreeMap keeps keys sorted by natural order or a Comparator, backed by a red-black tree with O(log n) operations, and supports range methods such as headMap and ceilingKey.
8. What is the difference between Comparable and Comparator?
Comparable defines a class's natural order through compareTo and is implemented by the class itself. Comparator is a separate object that defines an order, which lets you sort the same class in different ways without changing it.
List<Person> people = new ArrayList<>(); people.sort(Comparator.comparing(Person::lastName) .thenComparing(Person::firstName));9. What is a fail-fast iterator?
Iterators of ArrayList, HashMap, and similar collections track a modification count and throw ConcurrentModificationException if the collection is structurally changed during iteration by anything other than the iterator itself. Remove safely with iterator.remove() or removeIf(). Concurrent collections have weakly consistent iterators that do not throw.
10. How do you make a collection thread safe?
Use concurrent collections such as ConcurrentHashMap, CopyOnWriteArrayList (good for read-heavy data), or ConcurrentLinkedQueue. Collections.synchronizedList and similar wrappers lock every call and still require manual synchronization while iterating. Immutable collections need no synchronization at all.
11. What do List.of, Set.of, and Map.of return?
They return unmodifiable collections (Java 9 and newer). Adding, removing, or setting throws UnsupportedOperationException, and they reject null elements. Arrays.asList is different: it is fixed-size but write-through to the array. Use new ArrayList<>(List.of(...)) when you need a mutable copy.
12. What is type erasure?
Generics exist only at compile time. The compiler checks types and inserts casts, then erases the type parameters, so at runtime a List<String> and a List<Integer> are both just List. Consequences: you cannot use instanceof with a parameterized type, cannot create generic arrays, and cannot call new T().
13. What are wildcards, and what does PECS mean?
? extends T means some unknown subtype of T: you can read T values from it but not add to it (producer). ? super T means some supertype of T: you can add T values but only read Object (consumer). PECS stands for Producer Extends, Consumer Super.
static void copy(List<? super Integer> dest, List<? extends Integer> src) { for (Integer n : src) dest.add(n); }14. What is the difference between a Queue, a Deque, and a PriorityQueue?
Queue is first-in first-out. Deque allows insertion and removal at both ends, so it works as a queue or a stack; ArrayDeque is the usual implementation and replaces the legacy Stack class. PriorityQueue orders elements by natural order or a Comparator, so poll() returns the smallest element, not the oldest, and is backed by a binary heap.
15. How would you implement an LRU cache with the standard library?
Extend LinkedHashMap with access order enabled and override removeEldestEntry to evict when the size exceeds the limit.
class LruCache<K, V> extends LinkedHashMap<K, V> { private final int capacity; LruCache(int capacity) { super(16, 0.75f, true); // true = access order this.capacity = capacity; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > capacity; } }This version is not thread safe; wrap it or use a caching library for concurrent use.
Interview Tips
- Be ready to state time complexity for common operations on each collection.
- Practice drawing the HashMap bucket structure; it is the most common deep-dive question.
- Mention thread safety whenever you pick a collection in a coding round.