1

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

1
  • @assylias:The most general form should be infered, right? Commented Aug 15, 2012 at 11:09

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

1)Don't you mean ArrayList<E> implements Serializable?2) The most specific or the most generic type?
1) Yes ArrayList<Anything> implements Serializable 2) the most specific that applies to all 3. In your case, all three types are also Objects, but Serializable is more specific than Object so that's what is chosen.
If I change to: String s = pick("d", new ArrayList<String>()); it also does not compile.But this case is not clear why.It says: cannot convert from Serializable to String. How did it infer Serializable from this?All are Strings
Because Serializable is the most specific common supertype of both String and ArrayList.
Walk upwards the type hierarchy starting from Serializable, String, ArrayList<String> until you hit a common ancestor.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.