An unbounded wildcard is the type argument "?", a feature of generics in the Java language. This type argument represents some "unknown" type which was once present.
An unbounded wildcard is the type argument ?
, a feature of generics in the java language. This type argument represents some "unknown" type which was once present.
A wildcard is useful as a type argument in a situation where knowing the exact type is unnecessary:
public static void printElements(Iterable<?> anyIterable) {
for (Object element : anyIterable) {
System.out.println( element );
}
}
A type parameterized with a wildcard places restrictions on how an object can be used:
List<String> listOfString =
new LinkedList<>( Arrays.asList("a String") );
// We can assign any List to a List<?>, but, in
// doing so, we lose information about its original
// type argument.
List<?> listOfUnknown = listOfString;
// The wildcard therefore causes methods that once
// returned String to now return Object.
Object unknown0 = listOfUnknown.get( 0 );
// Compiler error:
// The wildcard prevents us from passing arguments
// to any method that once accepted String.
listOfUnknown.add( new Object() );
// Compiler error:
// Since we have lost knowledge of the original
// type, we can not pass String to the List either.
// (This is the case, even though we, as the programmer,
// can see this would be safe to do.)
listOfUnknown.add( "another String" );
The bounded-wildcard ? extends Object
is equivalent to the unbounded wildcard.
See also:
- Type Arguments of Parameterized Types in the Java Language Specification
- Official wildcards tutorial