Notes from moving a client codebase to Java 5 generics.
List<String> names = new ArrayList?<String>();
Map<String, List<Integer>> index = new HashMap?<String, List<Integer>>();
- You cannot do new T[] in a generic class. Use (T[]) new Object[n] and live with the warning, or pass a Class<T>.
- Wildcards: List<? extends Number> is read-only for practical purposes. List<? super Integer> lets you add Integers.
- Erasure means List<String> and List<Integer> are the same class at runtime. instanceof List<String> does not compile.
- Mixing raw types with generic code gives "unchecked" warnings everywhere. Fix them; they hide real bugs.
- Autoboxing is convenient and slow in tight loops. Integer == Integer compares references above 127. This one cost us a day.
Eclipse 3.1 handles generics fine. Ant needs source="1.5" target="1.5" in javac or you get confusing errors about "generics are not supported in -source 1.3".
Effective Java 2nd edition (when it comes out) will apparently cover this well. Until then, the Sun tutorial by Gilad Bracha is good.