Search code examples
javagenericswildcardtype-parameterbounded-wildcard

Why we can instantiate Pair<T> but we can't with Pair<?>


So why can we able to instantiate Pair but we can't able to instantiate Pair

Pair<T> p=new Pair<T>();

VS

Pair<?> p=new Pair<?>();

I know that <?> mean unknown type --> <? extends Object>

but isn't <T> mean the same thing ---> <T extends Object>

Anyone have an idea?


Solution

  • No, ? and T are not the same thing. ? represents a wildcard generic type parameter -- it could be anything at runtime. T represents a generic type parameter that will be a specific type at runtime -- we just don't know it at compile-time.

    That is, a List<?> could contain Strings, Integers, Floats, etc. A List<T> can only contain whatever T is parameterized as.