Skip to content
C

Collections Interview Questions

List maintains order and allows duplicates. Set does not allow duplicates and generally doesn't guarantee order. Map stores data as unique key-value pairs.


Q1. What is the difference between `List`, `Set`, and `Map`? List maintains order and allows duplicates. Set does not allow duplicates and generally doesn't guarantee order. Map stores data as unique key-value pairs.

Q2. What is the difference between `HashMap` and `TreeMap`? HashMap offers fast access but no guaranteed order. TreeMap keeps its entries sorted by key automatically, at the cost of somewhat slower performance.

Q3. What is the difference between `Comparable` and `Comparator`? Comparable defines a single, natural sorting order within the class itself, using compareTo(). Comparator defines sorting logic externally, allowing multiple different sort orders for the same class.

Q4. Why is `HashSet` faster than `TreeSet`? HashSet uses a hash-based internal structure for quick access without maintaining any order, while TreeSet must maintain sorted order at all times, requiring extra comparison work on every insertion.

Q5. Can a `HashMap` have a `null` key? Yes, HashMap allows exactly one null key and any number of null values. TreeMap, however, does not allow a null key.

Q6. What is the difference between `Iterator` and a simple for-each loop? An Iterator allows safe removal of elements while looping through a collection, using its own remove() method. A simple for-each loop does not support safely modifying the collection during iteration.

Key Points to Remember

  • Collections questions frequently compare two similar classes (ArrayList vs LinkedList, HashMap vs TreeMap) — always know the key trade-off.
  • Be ready to explain when you'd choose one collection over another, based on actual use-case needs.
  • Practice writing small code snippets using these collections, since interviewers often ask you to code, not just explain.