Sub topic 3
Reading with ? extends
A wildcard is the ? symbol in a generic type. It means "some type, but I won't say which one." Wildcards make your methods accept more kinds of lists.
Reading with ? extends
List<? extends Number> means "a list of some type that is a Number or a subclass of Number." It accepts a List<Integer> or a List<Double>. You can read Number values out of it. You cannot add to it, because the compiler does not know the real element type.
Writing with ? super
List<? super Integer> means "a list of Integer or a parent of Integer." It accepts a List<Integer>, a List<Number>, or a List<Object>. You can safely add an Integer to it. When you read from it, you only get back an Object.
Choosing Wildcards with PECS
PECS stands for "Producer Extends, Consumer Super." A producer is a list your method reads from, so it uses extends. A consumer is a list your method writes to, so it uses super.
import java.util.ArrayList;
import java.util.List;
public class WildcardDemo {
// Producer: we only read Numbers out
static double sum(List<? extends Number> nums) {
double total = 0;
for (Number n : nums) {
total += n.doubleValue();
}
return total;
}
// Consumer: we only put Integers in
static void addOneTwo(List<? super Integer> dst) {
dst.add(1);
dst.add(2);
}
public static void main(String[] args) {
List<Number> numbers = new ArrayList<>();
addOneTwo(numbers);
numbers.add(2.5);
System.out.println(sum(numbers)); // 5.5
}
}Type Erasure: What Happens at Runtime
Type erasure is when the compiler removes type arguments after it checks your code. At runtime, a List<String> and a List<Integer> are both just ArrayList.
import java.util.ArrayList;
import java.util.List;
public class ErasureDemo {
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
List<Integer> ints = new ArrayList<>();
System.out.println(strings.getClass() == ints.getClass()); // true
}
}What You Cannot Do with Generics
Erasure causes these limits:
| Not allowed | Why |
|---|---|
| `new T()` | T is unknown at runtime |
| `new T[10]` | Arrays need a real type |
| `static T field` | Static fields are shared by all type arguments |
| `List<int>` | Use `List<Integer>` instead |
Raw Types and Unchecked Warnings
A raw type is a generic type used without a type argument, such as List list. The compiler gives an "unchecked" warning, which means it can no longer check the element type for you. Avoid raw types in new code.
Heap Pollution and @SafeVarargs
Heap pollution happens when a variable of type List<String> actually holds other kinds of values. It can happen through raw types or through generic varargs (T... items). Only add @SafeVarargs to a varargs method when that method never stores anything into the varargs array.
Exercise
A method copies items from src into dst. Which wildcard should each parameter use?
Show answer
src is a producer, so it uses List<? extends T>. dst is a consumer, so it uses List<? super T>.