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;
}
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
.
由于您返回类型为T的对象并将其存储到Serializable类型的变量中,我猜编译器会在您的调用中推断出T是Serializable,因此String和ArrayList都有资格成为pick的参数。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.