Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

<T> on its own doesn't mean anything. The T type must be defined somewhere, either on your class or method level, e.g.:

public class PairFactory<T> {
  public Pair<T> makePair() {
    return new Pair<T>();
  }
}

In this case you decide on <T> during instantiation:

new PairFactory<String>();

This is a bit more involved:

public <T> Pair<T> makePair() {
  return new Pair<T>();
}

The compiler will try to figure out the type based on context, e.g.:

Pair<Date> p = makePair();

You are not allowed to instantiate with a wildcard as parameter, because it is generally useless. Instead, you can just use any reference type that is within the bounds of the type parameter (in this case, there are no bounds, so just any reference type):

class SuperCrazyBogusType { }
Pair<?> p = new Pair<SuperCrazyBogusType>();

(or you can use a more normal type like Object).

Do you see how weird that is? Yes, you can instantiate using any arbitrary type out there, even ones that have no relation to the rest of your program or what you are doing. And yes, it is 100% safe and correct, because all you wanted was a Pair<?> (a pair of some unknown type).

That points out why it is ridiculous, and why the syntax for doing this is unnecessary. There is almost nothing you can do with the Pair<?> you get (e.g. you cannot put any data into it), because you don't know the type parameter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top