Reputation: 10953
How this works without any Exceptoin ? Because T must be same in this case but one is String
and another one is ArrayList<Integer>
.
public static void main(String[] args) {
Serializable s = pick("d", new ArrayList<Integer>());
System.out.println("s:"+s);
}
static <T> T pick(T a1, T a2) {
return a2;
}
Upvotes: 2
Views: 82
Reputation: 25980
Since you return an object of type T and you store it into a variable of type Serializable, I guess that the compiler infers that T is Serializable in your call, so both String and ArrayList are eligible to be parameters of pick.
Upvotes: 1
Reputation: 178343
The compiler uses type inference to determine the type of T
. It picks the most specific type that works for all types considered. Here, the type of s
is Serializable
, and you pass in a String
and an ArrayList<Integer>
. Both String
and ArrayList
are Serializable
, with no other relation, so the inferred type for T
is Serializable
.
Upvotes: 7