Java Notes
35+ Java Collections Framework interview questions covering List, Set, Map, Queue, sorting, concurrent collections, and internal implementations.
1. What is the Java Collections Framework?
A unified architecture for representing and manipulating groups of objects. It includes:
- Interfaces: Collection, List, Set, Queue, Map
- Implementations: ArrayList, HashMap, TreeSet, etc.
- Algorithms: Collections.sort(), Collections.binarySearch()
3. How does HashMap work internally?
Put operation:
- Calculate
hashCode()of key - Compute bucket index:
hash & (n-1) - If bucket empty → insert new Node
- If collision → compare with
equals()
- Same key → update value
- Different key → add to linked list (or tree if >8 nodes)
Get operation:
- Calculate hash → find bucket
- Traverse linked list/tree using
equals() - Return value if found, null otherwise
4. Why is hashCode() and equals() contract important for HashMap?
If two objects are equal, they MUST have the same hashCode:
- Same hashCode → same bucket →
equals()checks actual equality - Different hashCode → different buckets → object never found!
// ❌ BROKEN — equals without hashCode
class Key {
int id;
public boolean equals(Object o) { return id == ((Key)o).id; }
// Missing hashCode! HashMap won't find the key.
}5. HashMap vs Hashtable vs ConcurrentHashMap
| Feature | HashMap | Hashtable | ConcurrentHashMap |
|---|---|---|---|
| Thread-safe | No | Yes (synchronized) | Yes (segment locks) |
| Null keys | One null key | No null keys | No null keys |
| Performance | Best (single thread) | Poor (full lock) | Good (concurrent) |
| Iterator | Fail-fast | Fail-fast | Weakly consistent |
| Since | Java 1.2 | Java 1.0 (legacy) | Java 1.5 |
6. HashSet vs TreeSet vs LinkedHashSet
| Feature | HashSet | TreeSet | LinkedHashSet |
|---|---|---|---|
| Order | No order | Sorted (natural/comparator) | Insertion order |
| Internal | HashMap | TreeMap (Red-Black tree) | LinkedHashMap |
| Null | One null | No null (comparison fails) | One null |
| Performance | O(1) | O(log n) | O(1) |
| Use case | Fast unique check | Sorted unique elements | Ordered unique elements |
7. What is the difference between fail-fast and fail-safe iterators?
| Feature | Fail-Fast | Fail-Safe |
|---|---|---|
| Behavior | Throws ConcurrentModificationException | No exception |
| Works on | Original collection | Copy of collection |
| Examples | ArrayList, HashMap iterator | ConcurrentHashMap, CopyOnWriteArrayList |
| Memory | No extra memory | Extra memory (copy) |
// Fail-fast
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
for (String s : list) {
list.remove(s); // ConcurrentModificationException!
}
// Safe removal
Iterator<String> it = list.iterator();
while (it.hasNext()) {
it.next();
it.remove(); // Safe — uses iterator's remove
}8. What is the difference between Comparable and Comparator?
// Comparable — natural ordering (inside the class)
class Student implements Comparable<Student> {
String name; int marks;
public int compareTo(Student other) {
return Integer.compare(this.marks, other.marks);
}
}
Collections.sort(students); // Uses compareTo
// Comparator — custom ordering (external)
Collections.sort(students, Comparator.comparing(Student::getName));
Collections.sort(students, (s1, s2) -> s2.marks - s1.marks); // Descending9. How does TreeMap maintain sorted order?
TreeMap uses a Red-Black Tree (self-balancing BST):
- Every node is either red or black
- Root is always black
- Red nodes can't have red children
- All paths from root to leaf have same number of black nodes
This ensures O(log n) for get, put, remove operations.
10. What is the difference between Iterator and Enumeration?
| Feature | Iterator | Enumeration |
|---|---|---|
| Methods | hasNext(), next(), remove() | hasMoreElements(), nextElement() |
| Remove | Supports remove() | No remove support |
| Collections | All modern collections | Legacy (Vector, Hashtable) |
| Fail-fast | Yes | No |
11-35. Additional Questions
11. What is a PriorityQueue? A queue where elements are ordered by priority (natural order or comparator). Internal: min-heap. peek/poll return the smallest element. O(log n) for add/remove.
12. ArrayDeque vs LinkedList for Queue operations? ArrayDeque is faster (no node allocation overhead), uses less memory. Prefer ArrayDeque for stack/queue operations.
13. What is Collections.unmodifiableList()? Returns a read-only view. Any modification throws UnsupportedOperationException. Note: underlying objects can still be modified if mutable.
14. What is the difference between Collection and Collections?
Collection— Interface (root of collection hierarchy)Collections— Utility class with static methods (sort, shuffle, synchronizedList, etc.)
15. What is the load factor in HashMap? Default is 0.75. When 75% of buckets are filled, the map resizes (doubles capacity). Higher load factor = less space, more collisions. Lower = more space, fewer collisions.
16. What happens when HashMap is resized? New array with double capacity is created. All entries are rehashed and redistributed. This is expensive — set initial capacity if you know the size.
17. How to make a collection thread-safe?
Collections.synchronizedList(list)— synchronized wrapperCopyOnWriteArrayList— copy on writeConcurrentHashMap— segment-level lockingCollections.unmodifiableList()— immutable (inherently thread-safe)
18. What is the difference between poll() and remove() in Queue?
remove()throws NoSuchElementException if emptypoll()returns null if empty
19. What are Spliterator and Stream?
Spliterator: Parallel-capable iterator that can split collection for parallel processingStream: Functional pipeline for processing sequences of elements
20. Can we store primitives in Collections? No directly. Autoboxing converts: int → Integer, double → Double, etc.
21. What is IdentityHashMap? Uses == (reference equality) instead of equals() for key comparison.
22. What is WeakHashMap? Entries are GC'd when keys have no other references. Used for caches.
23. What is EnumMap/EnumSet? Specialized implementations for enum keys — extremely fast (array-based internally).
24. How to sort a Map by values?
map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toLinkedHashMap(...));25. What is the difference between Arrays.sort() and Collections.sort()?
Arrays.sort(): For arrays. Uses dual-pivot quicksort (primitives), TimSort (objects)Collections.sort(): For Lists. Internally converts to array, sorts, copies back.
26-35. Rapid Fire:
- Vector vs ArrayList? Vector is synchronized (legacy), ArrayList is not.
- Stack class? Legacy, extends Vector. Use ArrayDeque instead.
- NavigableMap? Extended SortedMap with navigation methods (floorKey, ceilingKey).
- List.of() vs Arrays.asList()? List.of() is immutable; Arrays.asList() is fixed-size but mutable.
- What is CopyOnWriteArrayList? Creates copy on every write. Good for read-heavy scenarios.
- How to remove duplicates from List?
new ArrayList<>(new LinkedHashSet<>(list)). - What is a BlockingQueue? Queue that blocks on take when empty, blocks on put when full.
- TreeMap vs HashMap performance? HashMap O(1) average; TreeMap O(log n) always.
- What is Collections.singletonList()? Returns immutable list with exactly one element.
- Can HashMap have duplicate keys? No. Duplicate keys overwrite the previous value.
11. What is the difference between Iterator and ListIterator?
Answer:
| Feature | Iterator | ListIterator |
|---|---|---|
| Direction | Forward only | Bidirectional |
| Applicable to | All Collections | Only List |
| Operations | remove() only | add(), set(), remove() |
| Index | No index access | nextIndex(), previousIndex() |
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
ListIterator<String> li = list.listIterator();
while (li.hasNext()) {
String s = li.next();
if (s.equals("B")) li.set("B-Modified");
}
System.out.println(list);[A, B-Modified, C]
12. How does HashMap work internally?
Answer: HashMap internally uses an array of Node (bucket). The key's hashCode() is calculated, and index = hash & (n-1) determines the bucket. On collision, in Java 8, the linked list converts to a balanced tree (treeify at 8+ nodes). Rehashing occurs at load factor 0.75 (capacity doubles).
Map<String, Integer> map = new HashMap<>();
map.put("A", 1); // hash("A") → bucket index → store
map.put("B", 2);
System.out.println(map.get("A")); // hash("A") → find bucket → equals check → return value1
13. ConcurrentHashMap vs Hashtable vs SynchronizedMap?
Answer:
| Feature | ConcurrentHashMap | Hashtable | SynchronizedMap |
|---|---|---|---|
| Locking | Segment/bucket level | Entire map | Entire map |
| Null keys | Not allowed | Not allowed | Depends on wrapped map |
| Performance | High (concurrent reads) | Low | Low |
| Iterator | Fail-safe | Fail-fast | Fail-fast |
ConcurrentHashMap is preferred in production because it handles concurrent access efficiently.
14. What is the difference between Comparable and Comparator?
Answer: Comparable - defines natural ordering (implement in the class, compareTo() method). Comparator - defines custom/external ordering (separate class, compare() method). A class can implement only one Comparable, but can have multiple Comparators.
// Comparable - natural ordering
class Student implements Comparable<Student> {
String name; int marks;
public int compareTo(Student s) { return this.marks - s.marks; }
}
// Comparator - custom ordering
Comparator<Student> byName = (s1, s2) -> s1.name.compareTo(s2.name);
Comparator<Student> byMarksDesc = (s1, s2) -> s2.marks - s1.marks;15. What is a Fail-fast vs Fail-safe Iterator?
Answer: Fail-fast: Throws ConcurrentModificationException when the collection is modified during iteration (ArrayList, HashMap iterators). Fail-safe: Iterates on a copy, no exception is thrown (ConcurrentHashMap, CopyOnWriteArrayList).
16. How does TreeMap work internally?
Answer: TreeMap uses a Red-Black Tree (self-balancing BST). Keys remain in sorted order. O(log n) time complexity for get/put/remove. It implements the NavigableMap interface which provides range operations.
17. ArrayList vs LinkedList - when to use which?
Answer: ArrayList: Random access fast O(1), insertion/deletion slow O(n). LinkedList: Insertion/deletion fast O(1) at known position, random access slow O(n). Use ArrayList for read-heavy operations, LinkedList for frequent insertions/deletions at beginning/middle.
18. How does HashSet work internally?
Answer: HashSet internally uses a HashMap where elements are keys and the value is a dummy constant PRESENT. add() internally calls map.put(element, PRESENT). Uniqueness is ensured through hashCode() + equals().
19. What is PriorityQueue and how does it work?
Answer: PriorityQueue is a min-heap implementation where elements are ordered according to natural ordering or a Comparator. The smallest (or highest priority) element is at the head. O(log n) insertion, O(1) peek, O(log n) poll.
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(5); pq.add(1); pq.add(3);
System.out.println(pq.poll()); // Smallest first
System.out.println(pq.poll());1 3
20. What are EnumSet and EnumMap?
Answer: EnumSet - an optimized Set for enum constants (bit vector internally). EnumMap - an optimized Map for enum keys (array internally). Both are much faster than regular Set/Map because enum ordinals are used directly as indices.
21. What is WeakHashMap?
Answer: In WeakHashMap, keys are weak references. When no strong reference to a key remains, GC can collect it and the entry is automatically removed. Useful for caching where entries can be dropped under memory pressure.
22. Collections.unmodifiableList() vs List.of() (Java 9)?
Answer: Collections.unmodifiableList() provides an unmodifiable view of an existing list (the underlying list can still change). List.of() creates a truly immutable list (null not allowed, no structural changes possible even through the original reference).
23. How to use collections with Stream API?
Answer:
List<Integer> numbers = Arrays.asList(5, 3, 8, 1, 9, 2);
// Filter + Sort + Collect
List<Integer> result = numbers.stream()
.filter(n -> n > 3)
.sorted()
.collect(Collectors.toList());
System.out.println(result);[5, 8, 9]
24. Map mein iteration ke kitne ways hain?
Answer:
Map<String, Integer> map = Map.of("A", 1, "B", 2, "C", 3);
// 1. entrySet
for (Map.Entry<String, Integer> e : map.entrySet()) {}
// 2. keySet
for (String key : map.keySet()) {}
// 3. values
for (Integer val : map.values()) {}
// 4. forEach (Java 8)
map.forEach((k, v) -> System.out.println(k + "=" + v));25. What is LinkedHashMap?
Answer: LinkedHashMap maintains insertion order (HashMap does not maintain order). Internally uses HashMap + doubly-linked list. In access-order mode, you can implement an LRU Cache by overriding removeEldestEntry().
26. What is CopyOnWriteArrayList?
Answer: A thread-safe ArrayList where a copy of the internal array is made on every modification. No lock is applied on read operations (fast reads). Slow in write-heavy scenarios but ideal in read-heavy concurrent scenarios.
27. What is the Deque interface?
Answer: Double-Ended Queue - supports insertion/removal from both ends. ArrayDeque (array-based, faster) and LinkedList (node-based) are its implementations. Can be used in place of both Stack and Queue.
28. Collections.synchronizedList() vs CopyOnWriteArrayList?
Answer: synchronizedList() locks on every operation (single-threaded access). CopyOnWriteArrayList makes a copy on writes, reads are lock-free. Read-heavy → CopyOnWrite, balanced read/write → synchronizedList.
29. What is IdentityHashMap?
Answer: IdentityHashMap uses reference equality (==) instead of equals(). Two different objects are treated as different keys despite having the same content. Useful in serialization frameworks where object identity matters.
30. What is NavigableMap/NavigableSet?
Answer: Provides navigation methods: lowerKey(), higherKey(), floorKey(), ceilingKey(), subMap(), headMap(), tailMap(). TreeMap and TreeSet implement NavigableMap/NavigableSet. Useful for range queries.
Summary
In this chapter, we learned about Collections Interview Questions in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Collections Interview Questions.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, interview, questions, collections
Related Java Master Course Topics