Collections Interview Questions in Java
A school office stores information in different ways for different jobs: an attendance register in roll-number order, a box of lost-and-found items where order doesn't matter, and a cabinet of files looked up by student name. Java's Collections Framework offers the same choices as List, Set and Map, and knowing which to pick, and how they work inside, is one of the most tested topics in Java interviews. This page collects the questions asked most often, from basic to advanced.
Basic Questions
What is the difference between List, Set and Map?
A List keeps elements in order and allows duplicates, with access by index. A Set keeps no duplicates. A Map stores key-value pairs with unique keys. List and Set extend Collection; Map doesn't.
What is the difference between ArrayList and LinkedList?
ArrayList is backed by a resizable array: get(i) is O(1), adding at the end is O(1) on average, inserting in the middle is O(n). LinkedList is a doubly linked list: adding or removing at the ends is O(1), but get(i) is O(n). In practice ArrayList is faster for almost everything.
What is the difference between HashSet, LinkedHashSet and TreeSet?
HashSet: no order, O(1) operations. LinkedHashSet: keeps insertion order, O(1). TreeSet: keeps elements sorted, O(log n), using compareTo or a Comparator.
What is the difference between Collection and Collections?
Collection is the root interface for lists, sets and queues. Collections is a utility class with static methods such as sort, reverse, unmodifiableList and max.
Intermediate Questions
How does HashMap work internally?
It keeps an array of buckets. put computes the key's hashCode, mixes its bits, and picks a bucket index. Entries in the same bucket form a linked list, which turns into a balanced tree when it holds 8 or more entries. Inside a bucket, equals finds the matching key. When the map is 75 percent full, the array doubles and entries are redistributed.
Why must equals and hashCode be overridden together?
Because HashMap and HashSet use hashCode to find the bucket and equals to find the key inside it. If two equal objects had different hash codes, they would land in different buckets and lookups would fail.
What is the difference between HashMap and Hashtable?
Hashtable is a legacy class whose methods are all synchronized, and it allows no null keys or values. HashMap isn't synchronized and allows one null key and null values. For thread safety, use ConcurrentHashMap, not Hashtable.
What is the difference between Comparable and Comparator?
Comparable is implemented by the class itself (compareTo) and defines its natural order. A Comparator is a separate object (compare) that defines any other order, such as Comparator.comparing(Student::marks).reversed().
What is a fail-fast iterator?
An iterator that throws ConcurrentModificationException if the collection is structurally changed during iteration other than through the iterator itself. ArrayList and HashMap iterators are fail-fast. To remove while looping, use iterator.remove() or removeIf.
Advanced Questions
How does ConcurrentHashMap differ from a synchronized map?
Collections.synchronizedMap locks the whole map for every operation. ConcurrentHashMap locks only one bin when writing and doesn't lock for most reads, so many threads can work at once. Its iterators are weakly consistent and never throw ConcurrentModificationException.
What is the difference between unmodifiable and immutable collections?
Collections.unmodifiableList(list) is a read-only view: you can't change it, but changes to the original list show through. List.of and List.copyOf are truly immutable: nothing can change them.
Why should HashMap keys be immutable?
If a key's fields change after it is stored, its hash code changes, but the entry stays in the old bucket. The map can then no longer find it, and the entry is effectively lost.
What are sequenced collections?
Since Java 21, SequencedCollection and SequencedMap give ordered collections common methods: getFirst, getLast, addFirst, addLast, removeFirst, removeLast and reversed. List, Deque, LinkedHashSet, SortedSet and LinkedHashMap all implement them.
Collections in Code
Let's see ordering, removal during iteration and the mutable-key trap in one program.
import java.util.*;
public class CollectionFacts {
static class Key {
String name;
Key(String name) { this.name = name; }
@Override public boolean equals(Object o) {
return o instanceof Key k && k.name.equals(name);
}
@Override public int hashCode() { return name.hashCode(); }
}
public static void main(String[] args) {
List<String> names = List.of("Srihitha", "Navika", "Advitha", "Navika");
System.out.println(new HashSet<>(names).size() + " unique");
System.out.println("insertion order: " + new LinkedHashSet<>(names));
System.out.println("sorted: " + new TreeSet<>(names));
List<Integer> marks = new ArrayList<>(List.of(91, 34, 78, 22));
try {
for (Integer m : marks) {
if (m < 35) marks.remove(m);
}
} catch (ConcurrentModificationException e) {
System.out.println("for-each removal: "
+ e.getClass().getSimpleName());
}
marks.removeIf(m -> m < 35);
System.out.println("after removeIf: " + marks);
Map<Key, Integer> fees = new HashMap<>();
Key key = new Key("Navika");
fees.put(key, 15000);
key.name = "Navika Anamaneni"; // mutating a stored key
System.out.println("lookup after change: " + fees.get(key));
System.out.println("map still has " + fees.size() + " entry");
}
}3 unique
insertion order: [Srihitha, Navika, Advitha]
sorted: [Advitha, Navika, Srihitha]
for-each removal: ConcurrentModificationException
after removeIf: [91, 78]
lookup after change: null
map still has 1 entryExplanation:
- The four names contain one duplicate.
HashSetkeeps 3 in no particular order,LinkedHashSetkeeps first-seen order, andTreeSetsorts them. - Removing inside a for-each loop breaks the iterator's expectations and throws
ConcurrentModificationException.removeIfdoes it safely. - After the key's name changes, its hash code points to a different bucket, so
getreturnsnulleven though the entry is still in the map.
Interview Corner
Which collection would you use to count word frequencies?
A HashMap<String, Integer> with merge(word, 1, Integer::sum); a TreeMap if the output must be alphabetical. With streams: Collectors.groupingBy(w -> w, Collectors.counting()).
How do you make a collection thread-safe?
Prefer the concurrent classes: ConcurrentHashMap, CopyOnWriteArrayList (for read-mostly lists) and BlockingQueue implementations. Wrapping with Collections.synchronizedList works but locks everything.
Practice
- Easy: Sort a list of
Studentrecords by marks (highest first), then by name, usingComparator.comparing(...).reversed().thenComparing(...). - Harder: Find the first repeated element in
{4, 9, 2, 9, 4}using aHashSetin one pass (answer: 9).
Key Takeaways
Was this tutorial helpful?