Java Generics
Source: http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
Motivation
- Avoids annoying casts
- More accurately expresses intent; can't even put in the wrong type… or pass the wrong type of collection/impl.
Key Concepts
- Type Parameter
- Type Token
- Erasure — compiler removes type parameters when it generates bytecodes to support backward compatibility.
- Also means you don't have type information at runtime. :(
- Required for backward compatibility with Java 1.4 code.
- Generic Method
- Wildcards
- upper bound (e.g. "? extends Set" matches any class/interface that implements Set)
- lower bound (e.g. ? super
Use-Case Decisions
- Generic Methods vs. Wildcard Parameters
- Wildcard Parameters express the desire to have polymorphic handling of generics. Preferred whenever possible.
- Generic Methods are used to express dependencies between the types of parameters or return values.
- Class<T> — aka "Class Literal as a Run-time type Token"
- T, here is the compile-time type variable of the class being represented by Class. (e.g. String.class == Class<String>).
- This makes it possible to use the type in a generic context (think of the query example where MyDomainObject.class.newInstance() would be called, but returns an Object… instead you can declare references of type T… where T could be MyDomainObject.class)
- Wrapping legacy collections with Collections.checked___(Collection<?> c, Class) for fail-fast.
- Annotations make heavy used of Generics.
Rules
- You cannot create arrays of generics (e.g. List<String>[10] is not allowed).
- Avoid casting to Generics; since generics are not runtime variables, it doesn't help.
- While you can use Type Variables in casts they are not safe casts.
- Ditto with casting from one Generic to another (e.g. Collection<String> and Collection<StringBuffer>).
Uses of Generics
- Collections
- Type-Oriented classes (e.g. DAOs)
page revision: 0, last edited: 30 Nov 2010 20:55