Java collections interview questions (with answers)
15 min readUpdated
Collections come up in every Java interview, from the first technical round to senior roles, because you use them in every program. These questions cover what interviewers ask most, from List versus Set to how HashMap works inside.
The collections framework
1. What is the Java Collections Framework?
A set of interfaces (List, Set, Queue, Map) and ready-made classes (ArrayList, HashSet, ArrayDeque, HashMap, …) for storing and working with groups of objects, plus helpers in Collections and Arrays.
2. What is the difference between Collection and Collections?
Collection is the root interface of lists, sets and queues. Collections is a utility class of static methods such as sort, reverse, max and unmodifiableList.
3. Why is Map not a Collection?
A collection holds single elements; a map holds key-value pairs, so methods like add(element) do not fit. You can still view a map as collections through keySet(), values() and entrySet().
4. What is the difference between List, Set and Map?
A List keeps order and allows duplicates, with access by index. A Set does not allow duplicates. A Map stores values by unique keys.
5. What are generics and why do collections use them?
Generics let you say what type a collection holds: List<String>. The compiler then stops you from adding the wrong type and you need no casts when reading. At run time the type information is erased (type erasure).
Lists
6. What is the difference between ArrayList and LinkedList?
ArrayList is backed by an array: O(1) access by index, but inserting or removing in the middle shifts elements. LinkedList is a doubly linked list: O(1) add and remove at the ends, but O(n) to reach an index. ArrayList is the better default in almost every case.
7. How does ArrayList grow?
It starts with a backing array (capacity 10 on the first add). When the array is full it creates a new one about 1.5 times larger and copies the elements over. Adding is still O(1) on average (amortised).
8. What is the difference between an array and an ArrayList?
An array has a fixed size and can hold primitives (int[]). An ArrayList grows as needed, holds only objects (Integer, with autoboxing) and has many useful methods.
9. What is the difference between Arrays.asList(), List.of() and new ArrayList<>()?
new ArrayList<>() is fully changeable. Arrays.asList() is fixed-size: you can set but not add or remove. List.of() is completely unmodifiable and rejects null.
10. Why does remove() on a List<Integer> sometimes remove the wrong element?
list.remove(1) calls remove(int index) and removes the element at index 1. To remove the value 1, call list.remove(Integer.valueOf(1)).
import java.util.ArrayList;
import java.util.List;
public class RemoveTrap {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(List.of(10, 1, 20, 1));
list.remove(1); // removes index 1, the value 1
System.out.println(list);
list.remove(Integer.valueOf(20)); // removes the value 20
System.out.println(list);
}
}Output
[10, 20, 1] [10, 1]
Sets
11. How does HashSet work internally?
A HashSet is backed by a HashMap: each element is stored as a key with a shared dummy value. That is why it needs correct hashCode() and equals() and why add is O(1) on average.
12. What is the difference between HashSet, LinkedHashSet and TreeSet?
HashSet has no order, LinkedHashSet keeps insertion order, and TreeSet keeps elements sorted (O(log n), using compareTo or a Comparator).
13. How do you remove duplicates from a list but keep the order?
Pass it through a LinkedHashSet: new ArrayList<>(new LinkedHashSet<>(list)), or with streams list.stream().distinct().toList().
Maps
14. How does HashMap work internally?
It keeps an array of buckets. put takes the key's hashCode(), spreads its bits, picks a bucket and stores the entry; entries in the same bucket form a linked list that turns into a red-black tree when one bucket holds more than 8 entries (once the table has at least 64 buckets). get repeats the steps and uses equals() to find the key.
15. What happens when two keys have the same hash code?
That is a collision. Both entries live in the same bucket, and equals() decides which one you get. Many collisions make lookups slower, which is why a good hashCode() spreads values well.
16. What are the load factor and rehashing?
The load factor (default 0.75) decides how full the map may get. When the number of entries passes capacity × 0.75, the map doubles its bucket array and redistributes the entries (rehashing).
17. Can a HashMap have a null key?
Yes, one null key and any number of null values. TreeMap rejects a null key, and ConcurrentHashMap rejects null keys and values.
18. What is the difference between HashMap, LinkedHashMap and TreeMap?
No order, insertion order and sorted order. HashMap and LinkedHashMap are O(1) on average, TreeMap is O(log n) but offers floorKey, ceilingKey and ranges. See the full comparison guide linked below.
19. What is the difference between HashMap and Hashtable?
Hashtable is the old synchronized version: slower, and it allows no null keys or values. Use HashMap in single-threaded code and ConcurrentHashMap when threads share the map.
20. Why should map keys be immutable?
If a key object changes after it is put in the map, its hash code changes and the map looks in the wrong bucket, so the entry can no longer be found. String, Integer and records make safe keys.
21. How do you count how often each word appears?
Use a HashMap<String, Integer> with merge(word, 1, Integer::sum), or with streams groupingBy(w -> w, counting()). Use a TreeMap if you want the words printed in sorted order.
import java.util.Map;
import java.util.TreeMap;
public class WordFrequency {
public static void main(String[] args) {
String text = "to be or not to be";
Map<String, Integer> freq = new TreeMap<>();
for (String word : text.split(" ")) {
freq.merge(word, 1, Integer::sum);
}
System.out.println(freq);
}
}Output
{be=2, not=1, or=1, to=2}Sorting and iteration
22. What is the difference between Comparable and Comparator?
Comparable gives a class its natural order through compareTo() inside the class. A Comparator is a separate object, so you can sort the same class in many ways: Comparator.comparing(Student::marks).reversed().
23. What is a fail-fast iterator?
An iterator that throws ConcurrentModificationException as soon as it notices the collection was changed while iterating (other than through the iterator itself). ArrayList and HashMap iterators are fail-fast.
24. How do you safely remove elements while looping?
Use iterator.remove() or, simpler, list.removeIf(x -> condition). Removing with list.remove() inside a for-each loop throws ConcurrentModificationException.
25. What is a fail-safe iterator?
An iterator that works on a copy or a snapshot, so it does not throw when the collection changes. CopyOnWriteArrayList and the iterators of ConcurrentHashMap behave this way.
Queues and concurrency
26. What is the difference between Queue, Deque and Stack?
A Queue is first in, first out. A Deque allows adding and removing at both ends, so it works as a queue or a stack. Use ArrayDeque for both; the old Stack class is synchronized and outdated.
27. What is a PriorityQueue?
A queue that always gives you the smallest element first (by natural order or a Comparator), backed by a binary heap. offer and poll are O(log n). It is the standard tool for top-K and scheduling problems.
28. How do you make a collection thread safe?
Prefer the concurrent classes: ConcurrentHashMap, CopyOnWriteArrayList, ConcurrentLinkedQueue and the BlockingQueue family. Collections.synchronizedList() also works but locks the whole list on every call.
29. Why is ConcurrentHashMap faster than a synchronized map?
It does not lock the whole map. Reads take no lock, and writes lock only the affected bucket, so many threads can work on different keys at the same time. Use its atomic methods such as merge and computeIfAbsent for read-modify-write updates.
Quick revision table
| Class | Order | Duplicates | Typical cost |
|---|---|---|---|
ArrayList | Insertion order, by index | Yes | get O(1), add at end O(1) |
LinkedList | Insertion order | Yes | add/remove at ends O(1), get O(n) |
HashSet | None | No | O(1) average |
TreeSet | Sorted | No | O(log n) |
HashMap | None | Unique keys | O(1) average |
TreeMap | Sorted by key | Unique keys | O(log n) |
ArrayDeque | Both ends | Yes | O(1) at both ends |
PriorityQueue | Smallest first | Yes | offer/poll O(log n) |
Frequently asked questions
Which collections questions are asked most?
How HashMap works internally, ArrayList versus LinkedList, HashSet internals, Comparable versus Comparator, and fail-fast iterators.
Do I need to know the internal code of HashMap?
Know the idea: buckets, hash codes, equals(), collisions, treeification and resizing. You do not need to recite the source code.
Which collection should I use by default?
ArrayList for lists, HashMap for maps and HashSet for sets. Switch only when you need order, sorting or thread safety.
Learn it step by step
Practise this, step by step
Short lessons with quizzes, practice and interview questions, from your first program to job-ready.