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:
- Type parameters and raw types
- Bounds and generic methods
- Type erasure and type tokens
- Wildcards and PECS
Optionalas 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
Tso I can call methods on it. UnboundedTisObject.
Generics disappear at runtime; the compiler already proved the casts.
Arrays are reified and covariant. Lists are erased and invariant.
List.classis notList<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.
Optionalis for return values; empty collections stay collections.
Repository
findreturnsOptional. Servicegetthrows.
3. Speak these without notes
- Why
List<Integer>is not aList<Number>. - What erasure deletes, and what a
ParameterizedTypeReferencesaves. - PECS on
copy(src, dest). orElsevsorElseGet.- Why
Optionalis 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-up | Clear 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 entity | Return 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.