Module 4: Java Collections (The Boxes)
📚 Module 4: Java Collections
Focus: Moving from “One Item” to “A Group of Items.”
In Java, we don’t just use simple arrays. We use the Collections Framework. Think of this as a set of specialized boxes for organizing your data.
📦 Box 1: The ArrayList (The “Dynamic List”)
An ArrayList is like a standard list in Python. You can add items, remove items, and they stay in the order you put them.
🧩 The Analogy: The Grocery Receipt
- Items are listed in order.
- You can have two of the same item (Apples, Milk, Apples).
- You can always add more to the bottom.
In Java:
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Apple"); // Duplicates are allowed!📦 Box 2: The HashSet (The “Unique Bag”)
A Set is a box that forbids duplicates. If you try to add the same thing twice, it just ignores the second one.
🧩 The Analogy: The Guest List
- You only need to list a person’s name once.
- The order doesn’t matter; you just need to know if they are “In” or “Out.”
📦 Box 3: The HashMap (The “Dictionary”)
A Map stores data in Key-Value pairs. It’s the most powerful collection in Java.
🧩 The Analogy: The Coat Check
- The Key: The plastic ticket they give you. (Must be unique!).
- The Value: Your actual coat.
- If you give the key to the attendant, you get your coat back instantly.
In Java:
Map<Integer, String> userMap = new HashMap<>();
userMap.put(1, "Alice");
userMap.put(2, "Bob");
String name = userMap.get(1); // Returns "Alice"🏗️ Step 4: Generics (The “Label Maker”)
Notice the <String> or <Integer, String> in the code above? This is called Generics. It tells Java: “This box is ONLY for Strings.”
🥅 Module 4 Review
- List: Ordered items, duplicates allowed.
- Set: Unordered items, NO duplicates.
- Map: Key-Value pairs for fast lookups.
- Generics: Labeling your boxes for safety.