If we have generic method
class SClass{
public static <T> ArrayList<T> listFactory(){ return new ArrayList<T>(); }
}
we can define type-parameter T
explicit when this method is calling.
SClass.<?>listFactory();//compile error
SClass.<List<?>>listFactory();//ok
Why we cant invoke listFactory
with type parameter ?
, but can with List<?>
?
The rules of method invocation are described in the Java Language Specification. In this case we are interested with
A method invocation expression is used to invoke a class or instance method.
[...] TypeName . NonWildTypeArguments Identifier ( ArgumentListopt )
<?>
is a wild type, <List<?>>
is not.
As for the reason why, consider
SClass.<?>listFactory();//compile error
What could you even do with <?>
in listFactory()
? ?
is unknown. You wouldn't be able to do
new ArrayList<?>();
because the JLS prohibits it
It is a compile-time error if any of the type arguments used in a class instance creation expression are wildcard type arguments (§4.5.1).
But you couldn't use it with anything else either.