Type parameters and what is left of them at run time.
Key points, notes and past questions
Generics and Type Erasure
Type parameters sit inside every collection.
- A type you choose later
<T>after a class name declares a letter for the whole object.<E>before a return type declares a letter for that method.staticmembers cannot use the class's letter.- A bound uses
extendsand unlocks the bound's methods.
- What is left at run time
- No bound:
Object. Bound: the first bound. List<T>becomesList;T[]becomes the erased type with[].- Non-generic types and method bodies keep their meaning.
- The compiler inserts casts where a specific type is needed.
- No bound:
- Two methods, one signature
- Erase first, compare second.
- Letter names and return types do not separate methods.
- Different bounds give different erasures.
- The error is a compilation error, so nothing runs.
- Arrays bend, lists do not
- Child array fits parent array.
- Child list does not fit parent list.
- Arrays check each store while running.
- The compiler checks the written type of the argument, never the contents.
- Saying "some type"
?is one unknown type.? extends B: read asB, add nothing exceptnull.Box<?>accepts a box of any allowed type.- Use a named letter when two places must match.
- Containers and their limits
- A generic class reads like ordinary code once
Tis filled in. - A missing key:
containsKeyisfalse,getisnull. - No
new T(),new T[],instanceof Tor staticT. - All type arguments share one class and its static fields.
- A generic class reads like ordinary code once
Notes23 past questions in this topic
Week 4: Abstract classes, interfaces, private classes, callbacks, iteratorsWeek 6: Collections and mapsAll Java topics and weeks