</>

Technology

Core Java

Difficulty

Intermediate

Interview Question

What is the Java Collections Framework? Explain the key interfaces and classes.

Answer

Java Collections Framework

The Collections Framework is a unified architecture for storing and manipulating groups of objects. It provides interfaces, implementations, and algorithms.

Hierarchy

CODE
Collection (root interface)
├── List (ordered, duplicates allowed)
│   ├── ArrayList
│   ├── LinkedList
│   └── Vector (legacy, synchronized)
├── Set (no duplicates)
│   ├── HashSet (no order)
│   ├── LinkedHashSet (insertion order)
│   └── TreeSet (sorted order)
└── Queue (FIFO)
    ├── LinkedList
    ├── PriorityQueue
    └── ArrayDeque

Map (key-value pairs — NOT part of Collection)
├── HashMap (no order)
├── LinkedHashMap (insertion order)
├── TreeMap (sorted by key)
└── Hashtable (legacy, synchronized)

List — Ordered, Duplicates Allowed

Java
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Apple");       // duplicates OK
System.out.println(list.get(0));   // "Apple" — index access
System.out.println(list.size());   // 3
list.remove(0);                    // remove by index
Collections.sort(list);            // sort in-place

Set — No Duplicates

Java
Set<String> set = new HashSet<>();
set.add("Red");
set.add("Green");
set.add("Red");   // duplicate — ignored
System.out.println(set.size()); // 2 — not 3

// LinkedHashSet maintains insertion order
Set<String> ordered = new LinkedHashSet<>();

// TreeSet sorts alphabetically
Set<String> sorted = new TreeSet<>();

Map — Key-Value Pairs

Java
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 87);
scores.put("Alice", 98);  // overwrites previous value for "Alice"

System.out.println(scores.get("Alice")); // 98
System.out.println(scores.containsKey("Bob")); // true
System.out.println(scores.getOrDefault("Charlie", 0)); // 0

// Iterate
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
    System.out.println(entry.getKey() + " → " + entry.getValue());
}

Queue — FIFO

Java
Queue<String> queue = new LinkedList<>();
queue.offer("First");
queue.offer("Second");
queue.offer("Third");

System.out.println(queue.poll());  // "First" — removes and returns head
System.out.println(queue.peek());  // "Second" — returns without removing

Choosing the Right Collection

NeedUse
Ordered list with duplicates + index accessArrayList
Frequent insert/delete at beginningLinkedList
No duplicatesHashSet
No duplicates + sortedTreeSet
Key-value lookupHashMap
Key-value + sorted keysTreeMap
Thread-safe mapConcurrentHashMap

Follow AutomateQA

Related Topics