Generics and Classes
Generics parameterize types: Box stores T. The compiler checks assignments and removes casts. At runtime, due to type erasure, often only the raw form exists.
Advantage: fewer ClassCastExceptions, clearer APIs. Limitation: no new T[], no instanceof T with type parameter.
Example: List accepts add("a"), but not add(Integer).
| Wildcard | Read | Write |
|---|---|---|
| ? extends T | as T | usually forbidden |
| ? super T | as Object | insert T |
| ## Where used |
Typed repositories, event bus handlers, collection APIs. Generics shift class errors to compile time and are a prerequisite for readable library boundaries in large codebases.
Depth
A type parameter describes a family of classes with the same structure but different element types. The compiler checks insertion and removal consistently, which eliminates many runtime conversions.
Box<Integer> is not a subtype of Box<Number>. This invariance prevents, for example, writing a Double into a box that is actually an integer box via a supposedly Box<Number>.
Static members belong to the class and not to a specific type argument instantiation. Therefore, they cannot directly use the type parameter of the instance class. Methods can instead declare their own type parameters.
Difficulty levels
- Use a class type parameter in fields and methods.
- Justify invariance based on an unsafe write access.
- Distinguish between class and method type parameters.
Pitfalls
A single letter is not a concrete runtime type. Additionally, an unchecked cast only removes the compiler check, not the possibility of a later type error.
Tasks
Card Info
- Topic: Algorithms and Data Structures
- Difficulty: Intermediate
- Completed: 0 users