🗂️ 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")); } }