Wildcards, Arrays, and Generics in Java (Page 1 of 5 )
Explicit Type Invocation
Although it should not be needed often, a syntax does exist for invoking a generic method with specific parameter types. The syntax is a bit awkward and involves a class or instance object prefix, followed by the familiar angle bracket type list, placed before the actual method invocation. Here are some examples:
Integer i = MathUtilities.<Integer>max( 42, 42 ); String s = fooObject.<String>foo( "foo" ); String s = this.<String>foo( "foo" );
The prefix must be a class or object instance containing the method. One situation where you'd need to use explicit type invocation is if you are calling a generic method that infers its type from the assignment context, but you are not assigning the value to a variable directly. For example, if you wanted to pass the result of our makeTrap() method as a parameter to another method, it would otherwise default to Object.
Wildcard Capture
Generic methods can do one more trick for us involving taming wildcard instantiations of generic types. The term wildcard capture refers to the fact that generic methods can work with arguments whose type is a wildcard instantiation of a type, just as if the type were known:
<T> Set<T> listToSet( List<T> list ) { Set<T> set = new HashSet<T>(); set.addAll( list ); return set; }
// usage List<?> list = new ArrayList<Date>(); Set<?> set = listToSet( list );
The result of these examples is that we converted an unknown instantiation of List to an unknown instantiation of Set. The type variable T represents the actual type of the argument, list, for purposes of the method body. The wildcard instantiation must match any bounds of the method parameter type. But since we can work with the type variable only through its bounds types, the compiler is free to refer to it by this new name, T, as if it were a known type. That may not seem very interesting, but it is useful because it allows methods that accept wildcard instantiations of types to delegate to other generic methods to do their work.
Another way to look at this is that generic methods are a more powerful alternative to methods using wildcard instantiations of types. We'll do a little comparison next.