Java SE 8 Programmer II study materials
Java SE 8 Programmer II study resources

Java SE 8 Programmer II: Generics and Collections

Java SE 8 Programmer II · Work through your exam, one topic at a time.

All guide sections

Generics and Collections

Generics and Collections tests compile-time type safety, wildcard use, and choosing the right collection with correct equality and ordering contracts.

Core rules

  • Generic types are invariant: List<Integer> is not a List<Number>. Wildcards restore flexibility.
  • PECS: use ? extends T for producers (reading), ? super T for consumers (writing). You cannot add to ? extends T except null, and reading from ? super T gives Object.
  • Type erasure removes generic type information at runtime; therefore no new T(), no new T[], no instanceof List<String>, and no static field of a class type variable.
  • List preserves insertion order and allows duplicates; Set rejects duplicates by equals/hashCode; Map keys are unique; Queue/Deque define FIFO/LIFO operations.
  • HashSet/HashMap rely on consistent equals/hashCode; TreeSet/TreeMap rely on compareTo/Comparator returning 0 for equality.
  • Comparable defines natural ordering; Comparator supplies external ordering and supports chaining with thenComparing.

Worked example

void add(List<? super Integer> dst) { dst.add(1); } void sum(List<? extends Number> src) { for (Number n : src) { } } add(new ArrayList<Number>()) is legal; sum(new ArrayList<Integer>()) is legal. Inside add, dst.get(0) returns Object, not Integer.

Traps

  • Adding to a List<? extends Number> is illegal.
  • Generic arrays and instanceof with parameterized types are illegal.
  • Mutating a key after inserting it into a HashMap can make it unreachable.
  • TreeSet uses comparison, not equals, so inconsistent comparison breaks uniqueness.
  • List.remove(int) removes by index; remove(Object) removes by value.