Java Collection Interview Questions with Answers

1. What is the difference between List, Set, and Map?

Answer:

  • List: Ordered collection, allows duplicates. Examples: ArrayList, LinkedList.
  • Set: Unordered collection, does not allow duplicates. Examples: HashSet, TreeSet.
  • Map: Stores key–value pairs, keys are unique. Examples: HashMap, TreeMap.

2. How does HashMap work internally?

Answer:

  • Uses hashing: key’s hashCode() determines bucket location.
  • If multiple keys map to the same bucket, they are stored in a linked list or balanced tree (since Java 8).
  • Lookup is O(1) average, O(n) worst case.

3. Difference between HashMap and Hashtable

Answer:

  • HashMap is non-synchronized, allows one null key and multiple null values.
  • Hashtable is synchronized, does not allow null keys or values.
  • HashMap is faster and preferred in modern applications.

4. Fail-Fast vs Fail-Safe Iterators

Answer:

  • Fail-Fast: Throws ConcurrentModificationException if the collection is modified while iterating (e.g., ArrayList, HashMap).
  • Fail-Safe: Works on a copy of the collection, so no exception is thrown (e.g., ConcurrentHashMap, CopyOnWriteArrayList).

5. Difference between ArrayList and LinkedList

Answer:

  • ArrayList: Backed by a dynamic array, fast random access, slower insert/delete in middle.
  • LinkedList: Doubly linked list, fast insert/delete, slower random access.

6. Comparable vs Comparator

Answer:

  • Comparable: Defines natural ordering of objects using compareTo().
  • Comparator: Defines custom ordering using compare().

Example:

java

class Student implements Comparable<Student> {
    int age;
    public int compareTo(Student s) {
        return this.age - s.age;
    }
}

7. Difference between HashSet and TreeSet

Answer:

  • HashSet: Unordered, backed by HashMap, faster operations (O(1)).
  • TreeSet: Ordered (sorted), backed by TreeMap, slower operations (O(log n)).

8. ConcurrentHashMap vs SynchronizedMap

Answer:

  • ConcurrentHashMap: Allows concurrent reads and updates without locking the entire map.
  • SynchronizedMap: Locks the entire map for every operation, slower in multithreaded environments.

9. Difference between Iterator and ListIterator

Answer:

  • Iterator: Works with all collections, supports forward traversal only.
  • ListIterator: Works only with List, supports forward and backward traversal, can add/remove elements.

10. Why is Set not allowed to have duplicates?

Answer:

  • Set is based on mathematical set theory, which defines uniqueness.
  • Internally, HashSet uses hashing to ensure uniqueness, while TreeSet uses comparison.

Leave a Comment