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:

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

Main.java
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.

ShoppingList.java
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

Main.java
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.

StudentRecords.java
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

Step-by-Step Process

  1. Initialize the HashMap.
  2. Take input using Scanner.
  3. Use containsKey() to verify existence before calling get().

Expected Deliverables

Solve in Compiler