Collections Framework
Dashboard
Topic 17/30
Home › Collections Framework

🗂️ Collections Framework

A unified architecture for representing and manipulating collections of objects like lists, sets, and maps in Java.

1. Overview and Hierarchy

Unlike standard arrays, Collections can grow and shrink dynamically. The core interfaces are Collection (which branches into List, Set, and Queue) and Map (which stores key-value pairs independently of the Collection interface).

2. Lists (ArrayList & LinkedList)

Lists are ordered collections that allow duplicate elements.

ArrayListDemo.javaJava
import java.util.ArrayList;
import java.util.List;

public class ArrayListDemo {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Apple"); // Duplicates allowed

        System.out.println(list.get(1)); // Banana
        
        for (String item : list) {
            System.out.println(item);
        }
    }
}

3. Sets (HashSet & TreeSet)

Sets are collections that contain no duplicate elements.

SetDemo.javaJava
import java.util.HashSet;
import java.util.Set;

public class SetDemo {
    public static void main(String[] args) {
        Set<Integer> numbers = new HashSet<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(1); // Ignored

        System.out.println(numbers.size()); // 2
    }
}

4. Maps (HashMap)

Maps store key-value pairs. Keys must be unique.

HashMapDemo.javaJava
import java.util.HashMap;
import java.util.Map;

public class HashMapDemo {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();
        scores.put("Alice", 90);
        scores.put("Bob", 85);

        System.out.println("Alice's Score: " + scores.get("Alice"));
    }
}

🎯 Frequently Asked Interview Questions

Q1: How does HashMap work under the hood in Java 8+?
Answer: Uses an array of buckets storing Linked Nodes. Hash of key determines index. If bucket collisions exceed 8 items (and capacity >= 64), the bucket converts from a Linked List (O(n)) to a Red-Black Tree (O(log n)) for fast retrieval.
Q2: Difference between ArrayList and LinkedList?
Answer: ArrayList uses a dynamically resizing array (O(1) random access, O(n) insertion/deletion). LinkedList uses a doubly-linked node list (O(n) search access, O(1) node insertion/deletion).
Q3: How does ConcurrentHashMap achieve high concurrency?
Answer: Java 8 ConcurrentHashMap eliminates whole-table locks. It uses CAS (Compare-And-Swap) operations and lock-striping per bucket node (synchronized on bucket head), allowing concurrent reads and writes across different buckets.