Tuesday, January 31, 2012

Java unbounded wildcards

From Effective Java, 2nd edition:

If a type parameter appears only once in a method declaration, replace it with a wildcard.

For example, given a static method swapping 2 items in a list, prefer
public static void swap(List<?> list, int i, int j);
over
public static <E> void swap(List<E> list, int i, int j);
However, this implementation won't compile:
public static void swap(List<?> list, int i, int j) {
    list.set(i, list.set(j, list.get(i)));
}
because you can’t put any value except null into a List<?>. Instead, we will have to use:
public static void swap(List<?> list, int i, int j) {
    swapHelper(list, i, j);
}
// Private helper method for wildcard capture
private static <E> void swapHelper(List<E> list, int i, int j) {
    list.set(i, list.set(j, list.get(i)));
}