• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics: Wildcard capture  RSS feed

 
Ranch Hand
Posts: 110
Google App Engine Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I've read the following in an article about Generics and could not understand what it means by the given example:

9.1
Wildcard Capture
It should be pretty clear by now that given
Set<?> unknownSet = new HashSet<String>();
...
/** Add an element t to a Set s */
public static <T> void addToSet(Set<T> s, T t) {...}
The call below is illegal.
addToSet(unknownSet, “abc”); // illegal
It makes no difference that the actual set being passed is a set of strings; what
matters is that the expression being passed as an argument is a set of an unknown type,
which cannot be guaranteed to be a set of strings, or of any type in particular.
Now, consider
class Collections {
...
<T> public static Set<T> unmodifiableSet(Set<T> set) { ... }
}
...
Set<?> s = Collections.unmodifiableSet(unknownSet); // this works! Why?
It seems this should not be allowed; yet, looking at this specific call, it is perfectly
safe to permit it. After all, unmodifiableSet() does work for any kind of Set, regard-
less of its element type.
Because this situation arises relatively frequently, there is a special rule that allows
such code under very specific circumstances in which the code can be proven to be
safe. This rule, known as wildcard capture, allows the compiler to infer the unknown
type of a wildcard as a type argument to a generic method.


The generics used on the last example seems to be out of unmodifiableSet(...) method(if compared with the above one), but in counter part there is no type in the Collection class declaration on the example. So it could just being part of unmodifiableSet(...) method and so i can't understand why this concept applies to this last method and not in the first one, can anyone help me to understand?

Thanks in advance! :P
 
Ranch Hand
Posts: 50
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As per my understanding, the difference is in the method signature.

In first method, the arguments are: (Set<T> s, T t)
In second method, the arguments are: (Set<T> s)

When you call the first method passing a wildcard, the second argument is the actual cause of error since its not sure between the Types passed in the 2 arguments.
addToSet(unknownSet, “abc”);

First argument Set<?> is of some unknown type, but the second argument is of Type String.

When you call the second method, you only have to deal with Set<T>, which can handle the wildcard ? Type easily.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!