AI Hints
Home›Java Tutorial›ArrayList, Generics and Wrapper Classes
Java · Lesson 83 of 120

Generics

Lists of a certain type.

⏱ 2 min read▶ Video at 1:45:22🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

The angle brackets after ArrayList are called generics. They tell Java what type the list holds. So Java can catch mistakes, before your program runs.

  • The angle brackets
  • Say what's inside
  • Catch mistakes early

Type safety

This list is declared to hold strings. Adding hello is fine. Adding forty two isn't. Run it. Java refuses to compile. The list only accepts strings.

Main.javajava
import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        ArrayList<String> words = new ArrayList<>();
        words.add("hello");
        words.add(42);
    }
}
Output
Main.java:6: error: incompatible types: int cannot be converted to String
        words.add(42);
                  ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full
output
1 error
error: compilation failed

Your own generic class

Box, angle T, angle, is a generic class. T is a placeholder for a type. Whoever uses Box decides what T is. And get returns T, so no casting is ever needed.

Main.javajava
public class Box<T> {
    private T item;
    public void put(T item) { this.item = item; }
    public T get() { return item; }
}

Using Box

A box of strings, and a box of integers, from the same class. Get gives back the right type each time. So we can call to upper case on one, and multiply the other. Run it. Remember the milk, in capitals, and forty two.

Main.javajava
public class Main {
    public static void main(String[] args) {
        Box<String> note = new Box<>();
        note.put("Remember the milk");
        Box<Integer> number = new Box<>();
        number.put(7);
        String s = note.get();
        int n = number.get();
        System.out.println(s.toUpperCase() + " " + (n * 6));
    }
}
Output
REMEMBER THE MILK 42
Also uses Box.java
public class Box<T> {
    private T item;
    public void put(T item) { this.item = item; }
    public T get() { return item; }
}

The diamond

On the right, you can leave the angle brackets empty, like this. Java works out the type from the left side. That empty pair is called the diamond.

keyvalue
Left sideArrayList<String>
Right sidenew ArrayList<>()
<>the diamond
Ta type placeholder

Summary

Generics put a type in angle brackets, so Java knows what a list or class holds. Mistakes are caught before running. Next, why lists of numbers say Integer.

Key takeaways
  • List<String>
  • class Box<T>
  • new ArrayList<>()
Next up: Wrapper Classes and Autoboxing — Integer, Double and friends