Why prefer a wildcard to a type discriminator in a Java API (Re: Effective Java)
Posted
by
Michael Campbell
on Programmers
See other posts from Programmers
or by Michael Campbell
Published on 2011-09-04T21:09:28Z
Indexed on
2012/11/12
11:21 UTC
Read the original article
Hit count: 396
In the generics section of Bloch's Effective Java (which handily is the "free" chapter available to all: http://java.sun.com/docs/books/effective/generics.pdf), he says:
If a type parameter appears only once in a method declaration, replace it with a wildcard.
(See page 31-33 of that pdf)
The signature in question is:
public static void swap(List<?> list, int i, int j)
vs
public static void swap(List<E> list, int i, int j)
And then proceeds to use a static private "helper" function with an actual type parameter to perform the work. The helper function signature is EXACTLY that of the second option.
Why is the wildcard preferable, since you need to NOT use a wildcard to get the work done anyway? I understand that in this case since he's modifying the List and you can't add to a collection with an unbounded wildcard, so why use it at all?
© Programmers or respective owner