Java Collection Framework Interview Questions

Loading

The Java Collection Framework is a fundamental part of Java, and interviewers often test candidates on their understanding of collections, their implementations, and their use cases. Below are some common Java Collection Framework interview questions along with explanations and examples.


1. What is the Java Collection Framework?

The Java Collection Framework is a unified architecture for representing and manipulating collections of objects. It includes:

  • Interfaces: Define the behavior of collections (e.g., List, Set, Map).
  • Implementations: Concrete classes that implement the interfaces (e.g., ArrayList, HashSet, HashMap).
  • Algorithms: Methods for searching, sorting, and manipulating collections.

2. What are the main interfaces in the Collection Framework?

The main interfaces are:

  1. Collection: The root interface for all collections (except Map).
  2. List: An ordered collection that allows duplicates (e.g., ArrayList, LinkedList).
  3. Set: A collection that does not allow duplicates (e.g., HashSet, TreeSet).
  4. Map: A collection of key-value pairs (e.g., HashMap, TreeMap).
  5. Queue: A collection designed for holding elements prior to processing (e.g., PriorityQueue, LinkedList).

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

FeatureListSetMap
OrderOrdered (by insertion)Unordered (except LinkedHashSet)Unordered (except LinkedHashMap)
DuplicatesAllows duplicatesNo duplicatesNo duplicate keys
ImplementationArrayList, LinkedListHashSet, TreeSetHashMap, TreeMap

4. What is the difference between ArrayList and LinkedList?

FeatureArrayListLinkedList
Underlying Data StructureDynamic arrayDoubly linked list
Access TimeO(1) for random accessO(n) for random access
Insertion/Deletion TimeO(n) for add/remove at arbitrary positionsO(1) for add/remove at beginning/end
Use CaseFrequent read operationsFrequent add/remove operations

5. What is the difference between HashSet and TreeSet?

FeatureHashSetTreeSet
OrderUnorderedSorted (natural order or custom comparator)
PerformanceO(1) for add, remove, containsO(log n) for add, remove, contains
ImplementationUses HashMap internallyUses TreeMap internally
Use CaseFast access, no ordering neededSorted data, custom ordering

6. What is the difference between HashMap and TreeMap?

FeatureHashMapTreeMap
OrderUnorderedSorted (natural order or custom comparator)
PerformanceO(1) for put, get, removeO(log n) for put, get, remove
ImplementationUses hashingUses Red-Black Tree
Use CaseFast access, no ordering neededSorted data, custom ordering

7. What is the difference between HashMap and Hashtable?

FeatureHashMapHashtable
SynchronizationNot synchronizedSynchronized
Null Keys/ValuesAllows one null key and multiple null valuesDoes not allow null keys or values
PerformanceFasterSlower due to synchronization
LegacyPart of Java Collection FrameworkLegacy class

8. What is the difference between Comparable and Comparator?

FeatureComparableComparator
Interfacejava.lang.Comparablejava.util.Comparator
MethodcompareTo()compare()
UsageDefines natural orderingDefines custom ordering
ExampleCollections.sort(list)Collections.sort(list, comparator)

Example of Comparable:

class Student implements Comparable<Student> {
    private String name;
    private int age;

    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Student other) {
        return this.age - other.age; // Natural ordering by age
    }
}

Example of Comparator:

import java.util.Comparator;

class NameComparator implements Comparator<Student> {
    @Override
    public int compare(Student s1, Student s2) {
        return s1.getName().compareTo(s2.getName()); // Custom ordering by name
    }
}

9. What is the fail-fast and fail-safe behavior in collections?

  • Fail-Fast: Iterators throw a ConcurrentModificationException if the collection is modified while iterating (e.g., ArrayList, HashMap).
  • Fail-Safe: Iterators do not throw exceptions if the collection is modified while iterating (e.g., CopyOnWriteArrayList, ConcurrentHashMap).

10. What is the difference between Iterator and ListIterator?

FeatureIteratorListIterator
DirectionForward onlyForward and backward
MethodshasNext(), next(), remove()hasNext(), next(), hasPrevious(), previous(), add(), set()
Use CaseGeneral-purpose iterationList-specific iteration

11. What is the difference between PriorityQueue and LinkedList?

FeaturePriorityQueueLinkedList
OrderSorted (natural or custom order)Insertion order
PerformanceO(log n) for add/removeO(1) for add/remove at ends
Use CasePriority-based processingGeneral-purpose queue or list

12. What is the difference between Vector and ArrayList?

FeatureVectorArrayList
SynchronizationSynchronizedNot synchronized
PerformanceSlowerFaster
LegacyPart of Java Collection FrameworkPart of Java Collection Framework

13. What is the difference between Collections.synchronizedList() and CopyOnWriteArrayList?

FeatureCollections.synchronizedList()CopyOnWriteArrayList
SynchronizationSynchronizes the entire listCreates a new copy on modification
PerformanceSlower for frequent writesFaster for frequent reads
Use CaseGeneral-purpose synchronizationHigh-read, low-write scenarios

14. What is the difference between HashSet and LinkedHashSet?

FeatureHashSetLinkedHashSet
OrderUnorderedInsertion order
PerformanceFasterSlightly slower due to ordering
Use CaseFast access, no ordering neededMaintain insertion order

15. What is the difference between TreeMap and LinkedHashMap?

FeatureTreeMapLinkedHashMap
OrderSorted (natural or custom order)Insertion order or access order
PerformanceO(log n) for operationsO(1) for operations
Use CaseSorted dataMaintain insertion/access order

By understanding these concepts and practicing examples, you can confidently answer Java Collection Framework interview questions.

Leave a Reply

Your email address will not be published. Required fields are marked *