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.
foo(List<?> list) can take a List<String> or a List<Float>; the same cannot be said for foo(List<T> list).
<?>means this works with anything.<T>also means this works with anything, but is used if you need to refer to the typeTlater on in the code. Correct?Tduring declaration like inList<String>. That way you setTtoStringand every method that accepts an argument of typeTyou'll have to pass String and or a subtype of it (in case of String, there is no subtype).?means that you pass everthing, no matter what you passed before.