Java Foundations

Lesson 5 of 7

Collections and Generics

Java's Collections Framework provides ready-made, reusable data structures, and generics let those structures stay type-safe no matter what they hold.

import java.util.ArrayList;
import java.util.List;

List<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Go");
System.out.println(languages.get(0)); // "Java"

for (String lang : languages) {
    System.out.println(lang.toUpperCase());
}

List<String> is a generic type, the <String> tells the compiler "this list only ever holds Strings", so trying to .add(42) is a compile error, not a runtime surprise. ArrayList is the most common concrete implementation, a resizable, array-backed list.

Maps

import java.util.HashMap;
import java.util.Map;

Map<String, Integer> scores = new HashMap<>();
scores.put("Ada", 95);
scores.put("Grace", 98);

System.out.println(scores.get("Ada")); // 95
System.out.println(scores.getOrDefault("Bob", 0)); // 0, key doesn't exist

Map<String, Integer> associates keys with values, like Python's dict. getOrDefault avoids a null result (and a potential NullPointerException) when a key might not exist.

Why generics matter

Without generics, a collection could only hold Object, meaning you'd have to cast every single item back to its real type before using it, and the compiler couldn't catch a mistake until it crashed at runtime. Generics push that type checking to compile time, exactly where you want to catch bugs.

📝 Collections and Generics Quiz

Passing score: 70%
  1. 1.What does the <String> in List<String> guarantee?

  2. 2.Map.getOrDefault avoids returning null when a key does not exist in the map.

  3. 3.The most common resizable, array-backed implementation of List in Java is called ____.