CAP477 · Unit 4: Collections and functional Java
Generics and iterators
8 practice questions
Key points
- Type parameter T: compile-time safety, no primitives
- Invariance: List<Integer> is not List<Number>
- Erasure: same class at runtime
- Comparable natural order; Comparator external order
Generics let classes and methods work on a type parameter with compile-time type safety and no casts:
class Box<T> { T v; Box(T v){ this.v = v; } T get(){ return v; } }
static <T extends Comparable<T>> T mx(T a, T b) { return a.compareTo(b) >= 0 ? a : b; }
Box<String> b = new Box<>("hi") (diamond <> infers the type). Type parameters stand for reference types only (List<int> is illegal).
Bounds and wildcards: <T extends Comparable<T>> restricts T. List<? extends Number> can be read as Number (producer); List<? super Integer> can be written with Integer (consumer): PECS. List<Integer> is not a List<Number> (generics are invariant), so List<Number> ln = li; fails to compile.
Type erasure: generic types are erased to their bounds at run time, so new ArrayList<String>().getClass() == new ArrayList<Integer>().getClass() is true. Therefore no new T(), no instanceof List<String>, and no generic arrays.
Raw types (List raw) bypass checks: adding a String and an Integer compiles, and a later bad read throws ClassCastException (heap pollution). Avoid them.
Ordering: Comparable<T> gives a type its natural order via compareTo; Comparator<T> supplies an external order (Comparator.comparing(String::length).reversed()); list.sort(null) uses natural order.
Iterator: hasNext(), next(), remove(). Implementing Iterable<T> (a method iterator()) lets a class be used in for-each: a Range(3) prints 0 1 2.
Exam pitfall: List<String> cannot take add(5): "int cannot be converted to String".
Try two questions
Which interface must a class implement to be used directly in a for-each loop?
- Iterator
- Iterable
- Comparable
- Cloneable
Show the answer
B. Iterable supplies iterator(); the Range example prints '0 1 2'.
Is List<Integer> assignable to List<Number>?
- Only in a method parameter
- Only with a raw type
- Yes, because Integer extends Number
- No, generics are invariant
Show the answer
D. The compiler rejects List<Number> ln = li; use List<? extends Number> to read.