Zum Hauptinhalt springen

Week 5 Review — Generics and Optional

Goal

This review checks whether I can say erasure, PECS, and Optional’s job without mixing them.

Week 5 topics:

  1. Type parameters and raw types
  2. Bounds and generic methods
  3. Type erasure and type tokens
  4. Wildcards and PECS
  5. Optional as a return type

1. Week 5 big picture


Compile time Runtime
List<Order> ← compiler contract ArrayList (T gone)
JpaRepository<Order, Long> proxy + Class<Order> stored aside
List<? extends Number> read Number still just List
Optional<Order> findById a container object, or empty

HTTP: ParameterizedTypeReference<List<Order>> {}
anonymous subclass keeps List<Order> on its superclass

2. Core memory sentences

Generics are a compile-time contract on what a type contains.

Raw types are a compatibility hole. Do not use them in new code.

Bound T so I can call methods on it. Unbounded T is Object.

Generics disappear at runtime; the compiler already proved the casts.

Arrays are reified and covariant. Lists are erased and invariant.

List.class is not List<Order>. Use a type token when the element type matters.

PECS: producer extends, consumer super.

If I read and write, I want List<T>, not a wildcard.

Optional is for return values; empty collections stay collections.

Repository find returns Optional. Service get throws.


3. Speak these without notes

  1. Why List<Integer> is not a List<Number>.
  2. What erasure deletes, and what a ParameterizedTypeReference saves.
  3. PECS on copy(src, dest).
  4. orElse vs orElseGet.
  5. Why Optional is not a JPA field.

4. Tiny code proofs

Proof A — invariance

Assign List<Integer> to List<Number>. Confirm it does not compile. Change the parameter to List<? extends Number> and sum.

Proof B — erasure

Print new ArrayList<String>().getClass() == new ArrayList<Integer>().getClass().

Proof C — orElse eager

orElse(load()) where load prints. Call it on Optional.of(1) and see load still run. Repeat with orElseGet.


5. Common mix-ups from this week

Mix-upClear line
List<Integer> is-a List<Number>Invariant; use ? extends Number to read
instanceof List<String>Illegal; T is gone
getForObject(..., List.class)Need a ParameterizedTypeReference
Optional field on an entityReturn type only
orElse(queryDb())Use orElseGet for work

6. Interview drill

Open Java fundamentals:

  • What is type erasure? What survives at runtime?
  • When do you use Optional? When do you not?
  • Follow-up: PECS

Week 6 will reuse equals/hashCode and Comparable<T> on collections.


7. Ready for Week 6?

I am ready if I can explain why List.class is not enough for Jackson and why findById returns Optional while HTTP GET still returns 404.

Next: Week 6 Day 1 — Collection, List, and ArrayList