Cratylus
Cratylus

Reputation: 54094

Java generics and type inference

From Sun Tutorials for generics

Type Inference

To illustrate this last point, in the following example, inference determines that the second argument being passed to the pick method is of type String:

static <T> T pick(T a1, T a2) { return a2; }  
Serializable s = pick("d", new ArrayList<String>());

Origirally I thought that the idea is that you could use any parameter in place of T as long as it ends up with String. Example ArrayList<ArrayList<String>>

But then I saw that the following also compiled fine:
Serializable s = pick("d", new ArrayList<Integer>());
It seems that T is inferred to be a Serializable and not a String?

So what is the meaning of the statement

inference determines that the second argument being passed to the pick method is of type String

Upvotes: 1

Views: 231

Answers (1)

assylias
assylias

Reputation: 328873

In this case, the 3 types are Serializable, String, ArrayList<String>.

  • Serializable does not extend anything
  • String implements Serializable and other unrelated stuff
  • ArrayList<String> implements Serializable and other unrelated stuff

So the most specific type that applies to all 3 is Serializable.

If you replace the call with Serializable s = pick("d", new Object()); for example, it does not compile any longer because the most specific type is now Object and you can't cast Object to Serializable.

Upvotes: 2

Related Questions