Chapter 8 — Java Collections Framework
📚 Chapter Overview
Storing single items in variables is not enough for real apps. In this chapter, you will learn how to manage groups of objects using the Collections Framework, specifically ArrayList (dynamic lists) and HashMap (key-value mapping).
Learning Objectives:
- Understand the Hierarchy of the Collections Framework.
- Master
ArrayListfor ordered data. - Use
HashMapfor fast data lookup.
8.1 ArrayList: Dynamic Lists
Part 1 — Definition
An ArrayList is a resizable array found in the java.util package. Unlike standard arrays, which have a fixed size, an ArrayList can grow or shrink automatically as items are added or removed. It maintains the Insertion Order of elements.
Part 2 — Syntax
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add("Item");
list.remove(0);
Part 3 — Example
Problem: Manage a "Shopping List" where users can add items.
ArrayList<String> cart = new ArrayList<>();
cart.add("Laptop");
cart.add("Mouse");
for(String item : cart) {
System.out.println("Item in cart: " + item);
}
Part 4 — Video
Video: Coming Soon
8.2 HashMap: Key-Value Mapping
Part 1 — Definition
A HashMap stores items in "Key/Value" pairs. You access an item by its key (e.g., an ID), which makes it incredibly fast for searching. Keys must be unique, while values can be duplicated.
Part 2 — Syntax
import java.util.HashMap;
HashMap<Integer, String> map = new HashMap<>();
map.put(101, "Ali");
String val = map.get(101);
Part 3 — Example
Problem: Store student IDs and their corresponding names.
HashMap<Integer, String> students = new HashMap<>();
students.put(1, "John");
students.put(2, "Sara");
System.out.println("ID 1 is: " + students.get(1));
Part 4 — Video
Video: Coming Soon
🏆 Chapter Challenge
Challenge Objective
Build a "Mini Contact Manager" using Java Collections.
Requirements
- Use a
HashMap<String, String>where key is "Name" and value is "Phone Number". - Allow the user to search for a number by entering a name.
- Display a message "Contact not found" if the name doesn't exist.
Step-by-Step Process
- Initialize the HashMap.
- Take input using
Scanner. - Use
containsKey()to verify existence before callingget().
Expected Deliverables
ContactManager.javasource code.