Useful JavaExtra· 35 min read

Collections (ArrayList & HashMap)

ArrayList grows and shrinks; HashMap stores key-value pairs — both beat plain arrays for everyday work.

What you will learn

  • Use an ArrayList that resizes itself
  • Store key-value pairs in a HashMap
  • Pick the right collection for a task

Beyond fixed arrays

A plain array has a fixed size — you must know how many items up front. Real programs rarely do. Java collections are smarter containers. The two you will use most are ArrayList and HashMap.

ArrayList: a list that grows

An ArrayList is like an array that can grow and shrink as you add or remove items. You never set its size.

An ArrayList of tasks that grows and shrinks
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> tasks = new ArrayList<>();
        tasks.add("Email Asha");
        tasks.add("Buy milk");
        tasks.add("Call bank");

        tasks.remove("Buy milk");

        System.out.println("Tasks left: " + tasks.size());
        for (String t : tasks) {
            System.out.println("- " + t);
        }
    }
}

Note: Output: Tasks left: 2 - Email Asha - Call bank We added three tasks and removed one, with no fixed size. add, remove and size are the everyday methods. The <String> part says this list holds Strings.

HashMap: key to value

A HashMap stores pairs: a unique key and its value. It is perfect for look-ups, like a phone book (name to number).

A HashMap from names to ages
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> ages = new HashMap<>();
        ages.put("Asha", 25);
        ages.put("Ravi", 30);

        System.out.println("Ravi is " + ages.get("Ravi"));
        System.out.println("Has Asha? " + ages.containsKey("Asha"));
    }
}

Note: Output: Ravi is 30 Has Asha? true put stores a key-value pair, get looks up a value by its key, and containsKey checks if a key exists. Here keys are Strings (names) and values are Integers (ages).

Looping over every pair

To visit all the pairs in a HashMap, loop over its keys with keySet(), then use get to fetch each value:

Looping over the keys of a HashMap to print every pair
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> ages = new HashMap<>();
        ages.put("Asha", 25);
        ages.put("Ravi", 30);

        for (String name : ages.keySet()) {
            System.out.println(name + " is " + ages.get(name));
        }
    }
}

Note: Output: Asha is 25 Ravi is 30 ages.keySet() gives every key (Asha, Ravi). For each key we call ages.get(name) to read its value. Note a HashMap does NOT keep things in the order you added them, so the lines may print in a different order — that is normal for a HashMap.

Which one to use?

NeedUseWhy
An ordered list that changes sizeArrayListEasy add/remove, keeps order
Look up a value by a keyHashMapFast key to value lookup
A fixed number of itemsA plain arraySimple and lightweight

Tip: Collections only hold objects, so use the capital-letter wrapper types inside the angle brackets: Integer not int, Double not double. Java converts between them automatically when you add or read.

Q. You want to store and look up phone numbers by a person name. Which collection fits best?

Answer: A HashMap maps a key (the name) to a value (the number), giving fast look-ups by key — exactly what a phone book needs.

✍️ Practice

  1. Create an ArrayList of your favourite movies, add four, remove one, and print the rest.
  2. Build a HashMap of three countries to their capitals and look one up with get.

🏠 Homework

  1. Make a HashMap that maps student names to their scores, then loop over it and print each name with its score.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →