Sub topic 1
Why Generics Exist
A collection is an object that holds other objects, like a List. Before Java added generics, a list could hold anything at all. That freedom caused bugs.
The Problem with Raw Types
A raw type is a generic class that is used without saying what type it holds. A cast is a note to the compiler, such as (String), that says "treat this value as a String."
import java.util.ArrayList;
import java.util.List;
public class RawListDemo {
public static void main(String[] args) {
List list = new ArrayList(); // raw type
list.add("hello");
list.add(42); // compiles: anything can go in
String first = (String) list.get(0); // cast required
String second = (String) list.get(1); // ClassCastException at runtime
}
}The compiler accepts this code without an error. The program crashes only when it runs. Generics let you tell the compiler what type goes in a class, so it catches this kind of mistake before the program ever runs.
Your First Generic Class
A type parameter is a placeholder for a type, written in angle brackets. The caller fills it in later.
public class Box<T> {
private T value;
public Box(T value) { this.value = value; }
public T get() { return value; }
public void set(T value) { this.value = value; }
public static void main(String[] args) {
Box<String> box = new Box<>("hi");
String s = box.get(); // no cast needed
System.out.println(s);
// box.set(5); // compile error: 5 is not a String
}
}Naming Type Parameters
By convention, Java programmers name type parameters with a single capital letter:
| Name | Usual meaning |
|---|---|
| T | Type |
| E | Element (in a collection) |
| K | Key (in a map) |
| V | Value (in a map) |
The Diamond Operator
In new Box<>("hi"), the empty <> is called the diamond operator. The compiler looks at the declared type, Box<String>, and works out T for you. This is called type inference.
Multiple Type Parameters
A class can have more than one type parameter. You separate them with commas.
public class Pair<K, V> {
private final K key;
private final V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() { return key; }
public V getValue() { return value; }
public static void main(String[] args) {
Pair<String, Integer> age = new Pair<>("Ada", 36);
System.out.println(age.getKey() + " is " + age.getValue());
}
}Exercise
You write Box<Integer> b = new Box<>(10); and then b.set("ten");. What happens, and when?
Show answer
The compiler reports an error, because T is Integer and "ten" is a String. You find the mistake when you compile, before the program runs.