Generics
You've already used generics: List<String>, Map<String, Integer>. Generics let a class or method work with any type while keeping full type safety: the compiler knows exactly what's inside a List<String> and stops you from putting a number in it.
Why generics exist
Before generics (Java 5), collections held plain Objects. You had to cast everything back out, and mistakes only showed up as crashes at run time:
import java.util.ArrayList;
import java.util.List;
public class Main {
@SuppressWarnings({"rawtypes", "unchecked"})
public static void main(String[] args) {
List names = new ArrayList(); // a "raw" list: no type parameter
names.add("Asha");
names.add(42); // nothing stops this…
for (Object o : names) {
String s = (String) o; // …until this cast crashes
System.out.println(s.toUpperCase());
}
}
}ASHA Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap') at Main.main(Main.java:11)
With List<String>, the line names.add(42) simply doesn't compile, and no casts are needed. The bug is caught before the program runs.
A generic class
<T> declares a type parameter: a placeholder for a type chosen by whoever uses the class:
class Box<T> {
private final T value;
Box(T value) { this.value = value; }
T get() { return value; }
boolean isEmpty() { return value == null; }
@Override
public String toString() { return "Box[" + value + "]"; }
}
public class Main {
public static void main(String[] args) {
Box<String> nameBox = new Box<>("Asha");
Box<Integer> numberBox = new Box<>(42);
String name = nameBox.get(); // no cast needed
int doubled = numberBox.get() * 2;
System.out.println(name.toUpperCase() + " " + doubled);
System.out.println(nameBox + " " + numberBox);
}
}ASHA 84 Box[Asha] Box[42]
Common type parameter names: T (type), E (element), K/V (key/value), R (result).
Several type parameters
class Pair<K, V> {
private final K key;
private final V value;
Pair(K key, V value) { this.key = key; this.value = value; }
K key() { return key; }
V value() { return value; }
@Override public String toString() { return key + "=" + value; }
}
public class Main {
public static void main(String[] args) {
Pair<String, Integer> age = new Pair<>("Asha", 31);
Pair<String, Boolean> flag = new Pair<>("darkMode", true);
System.out.println(age + ", " + flag);
System.out.println(age.value() + 1);
}
}Asha=31, darkMode=true 32
Generic methods
A method can have its own type parameter, declared before the return type:
import java.util.List;
public class Main {
static <T> T firstOrDefault(List<T> items, T fallback) {
return items.isEmpty() ? fallback : items.get(0);
}
static <T> void printAll(List<T> items) {
for (T item : items) System.out.print(item + "; ");
System.out.println();
}
public static void main(String[] args) {
System.out.println(firstOrDefault(List.of("x", "y"), "none"));
System.out.println(firstOrDefault(List.<Integer>of(), -1));
printAll(List.of(1, 2, 3));
printAll(List.of("a", "b"));
}
}x -1 1; 2; 3; a; b;
The compiler infers T from the arguments, so you rarely write it explicitly.
Bounded types: T extends …
Sometimes T must be capable of something. <T extends Comparable<T>> means "any type that can be compared to itself":
import java.util.List;
public class Main {
static <T extends Comparable<T>> T max(List<T> items) {
T best = items.get(0);
for (T item : items) {
if (item.compareTo(best) > 0) best = item;
}
return best;
}
static double sum(List<? extends Number> numbers) { // Integer, Double, Long…
double total = 0;
for (Number n : numbers) total += n.doubleValue();
return total;
}
public static void main(String[] args) {
System.out.println(max(List.of(3, 9, 4)));
System.out.println(max(List.of("pear", "apple", "zucchini")));
System.out.println(sum(List.of(1, 2, 3)) + " " + sum(List.of(1.5, 2.5)));
}
}9 zucchini 6.0 4.0
Wildcards: ?
A List<Integer> is not a List<Number>, even though an Integer is a Number. (If it were, you could add a Double to a list of integers.) Wildcards express flexible relationships:
| Wildcard | Meaning | Typical use |
|---|---|---|
List<?> |
A list of some unknown type | Read elements as Object |
List<? extends Number> |
Number or any subtype | You read numbers from it ("producer") |
List<? super Integer> |
Integer or any supertype | You write integers into it ("consumer") |
The memory aid is PECS: Producer Extends, Consumer Super.
import java.util.ArrayList;
import java.util.List;
public class Main {
static void addNumbers(List<? super Integer> target) { // a consumer of Integers
for (int i = 1; i <= 3; i++) target.add(i);
}
public static void main(String[] args) {
List<Number> numbers = new ArrayList<>();
List<Object> objects = new ArrayList<>();
addNumbers(numbers);
addNumbers(objects);
System.out.println(numbers + " " + objects);
}
}[1, 2, 3] [1, 2, 3]
Type erasure
Generics exist only at compile time. After checking, the compiler erases them, so at run time a List<String> and a List<Integer> are the same class:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> a = new ArrayList<>();
List<Integer> b = new ArrayList<>();
System.out.println(a.getClass() == b.getClass());
}
}true
Consequences: you can't write new T(), can't use primitives as type arguments (List<int> → use List<Integer>), and can't check if (x instanceof List<String>).
A generic data structure: a simple cache
import java.util.LinkedHashMap;
import java.util.Map;
class LruCache<K, V> extends LinkedHashMap<K, V> {
private final int capacity;
LruCache(int capacity) {
super(16, 0.75f, true); // true = order by most recent access
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity; // evict the least recently used entry
}
}
public class Main {
public static void main(String[] args) {
LruCache<String, Integer> cache = new LruCache<>(2);
cache.put("a", 1);
cache.put("b", 2);
cache.get("a"); // touch a: now b is the least recently used
cache.put("c", 3); // evicts b
System.out.println(cache.keySet());
}
}[a, c]
That's a working LRU cache in a dozen lines, fully type-safe for any key and value types.
Practice
- Write a generic
Stack<T>class withpush,pop,peekandisEmpty, backed by anArrayList<T>. - Write
static <T> List<T> repeat(T item, int times). - Write
static <T extends Comparable<T>> boolean isSorted(List<T> list).
1.What's the main benefit of generics?
2.Can you write List<int>?
3.Which signature accepts a List