Java · Module 8 · Lesson 11 min read

Generics & Lists

Why generics?

Generics let a class work with any type while keeping type safety:

Java
List<String> names = new ArrayList<>();
names.add("Ana");
names.add(42);          // ❌ compile error, caught early!
String first = names.get(0);   // no cast needed

The empty <> is the diamond operator; Java infers the type.

Write your own generic class

Java
class Box<T> {
    private T item;
    void put(T item) { this.item = item; }
    T get() { return item; }
}
Box<Integer> b = new Box<>();
  • Bounded types: <T extends Number> accepts only numbers.
  • Wildcards: List<? extends Number> lets you read numbers; List<? super Integer> lets you add integers.

Wrapper classes & autoboxing

Generics only work with objects, so use wrappers: Integer, Double, Boolean, Character… List<int> ❌ → List<Integer> ✅. Java converts between int and Integer automatically (autoboxing).

ArrayList vs LinkedList

ArrayListLinkedList
Get by index⚡ fast🐢 slow
Add/remove at start🐢 slow⚡ fast
Memorylessmore
💡 Use ArrayList by default.

Everyday List methods

add(x), add(i, x), get(i), set(i, x), remove(i) / remove(obj), size(), contains(x), indexOf(x), isEmpty(), clear()

Immutable lists

List.of("a", "b") creates a list that can't be changed. Calling add throws UnsupportedOperationException.

Example

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

public class Backpack {
    public static void main(String[] args) {
        List<String> items = new ArrayList<>();
        items.add("Sword");
        items.add("Potion");
        items.add("Map");
        items.add(1, "Shield");             // insert at index 1

        items.remove("Map");
        System.out.println(items);          // [Sword, Shield, Potion]
        System.out.println(items.size());   // 3
        System.out.println(items.contains("Potion")); // true

        for (String item : items) System.out.println("🎒 " + item);
    }
}