Java 1.5 Tiger A Developers Notebook [Electronic resources]

David Flanagan, Brett McLaughlin

نسخه متنی -صفحه : 131/ 33
نمايش فراداده

2.9 Using Type Wildcards

NOTE

While I'm sure plenty of folks disagree, I think production code shouldn't issue warnings.

So now you've got generic types figured out, and even understand all the unchecked warnings your code is generating. Still, here are times when you really do want a plain old List, or Map, or whatever, without parameterization. This is going to result in unchecked errors, unless you employ the generics wildcard.

2.9.1 How do I do that?

To illustrate the problem, here's a really simple method that prints out all the members of a List:

    public void printList(List list, PrintStream out) throws IOException {
for (Iterator i = list.iterator( ); i.hasNext( ); ) {
out.println(i.next( ).toString( ));
}
}

NOTE

Since writing this, later versions of the compiler don't throw warnings here. Still, it makes a good point, so I've left it in for you.

The problem is that this generates unchecked warnings, something you should avoid whenever possible. What you're really saying, though, is that printList( ) takes any List. This is where the wildcard operator comes in, which for generics is a question mark (?). Make the following change:

    public void printList(List<?> list, PrintStream out) throws IOException {
for (Iterator<?> i = list.iterator( ); i.hasNext( ); ) {
out.println(i.next( ).toString( ));
}
}

You've now expressed in syntax what you meantany type is acceptable, and the unchecked warnings go away.

2.9.2 What about...

...using List<Object> to get around this same problem? You might want to review Generics and Type Conversions, and see if you really want to do that. A List<Integer> cannot be passed to a method that takes a List<Object>, remember? So your printList( ) method would be limited to collections defined as List<Object>, which isn't much use at all. In these cases, the wildcard really is the only viable solution.

You should also be thinking about the declaration of methods in classes like this:

    public interface List<E> {
public E get( );
public void add(E value);
}

NOTE

You would read this as a "list of unknown".

Since you've declared the list as a List<?>, get( ) now returns an Object, which is as close to "unknown" as Java gets. At the same type, this is very different from a List<Object>, which can only work with Objects. Where things get even odder is for the add( ) and other methods that take a parameter that matches the type of the collection. Since the compiler cannot check to ensure type-safety, it rejects any call to add( ), addAll( ), and set( ) for a List<?>. In other words, supplying the wildcard to a generic type effectively makes it read-only.