In the Java generics tutorial it says that <?>
in a generic method means "unknown".
But I don't understand how <?>
is different than <T>
. Both mean that you can pass in any type-parameter you'd like. Please explain this operator.
In the Java generics tutorial it says that <?>
in a generic method means "unknown".
But I don't understand how <?>
is different than <T>
. Both mean that you can pass in any type-parameter you'd like. Please explain this operator.
The following excerpts come from http://docs.oracle.com/javase/tutorial/java/generics/wildcards.html
In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific). The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype.
And another:
The unbounded wildcard type is specified using the wildcard character (?), for example, List. This is called a list of unknown type. There are two scenarios where an unbounded wildcard is a useful approach:
- If you are writing a method that can be implemented using functionality provided in the Object class.
- When the code is using methods in the generic class that don't depend on the type parameter. For example, List.size or List.clear. In fact, Class is so often used because most of the methods in Class do not depend on T.
The second bullet makes the biggest distinction. Use '?' When you don't need to call operations on the actual type. See the link provided if you need more details. There are several sub sections under this wild cards section that cover different points so don't stop with just the page you are directed to.