为什么这个通用的Java方法接受两个不同类型的对象? [英] Why does this generic java method accept two objects of different type?
问题描述
此方法应获取两个相同类型的对象,并随机返回其中一个对象:
This method shall take two objects of the same type and return one of those objects by random:
public static <T> T random(T o1, T o2)
{
return Math.random() < 0.5 ? o1 : o2;
}
现在,为什么编译器会接受两个具有不同类型的参数?
Now, why does the compiler accept two parameters with distinctive types?
random("string1", new Integer(10)); // Compiles without errors
既然我知道两个参数都被隐式地转换了,我想知道为什么编译器在调用以下方法时会确实抱怨:
Now that I know that both parameters are getting implicitly upcasted, I wonder why the compiler does complain when calling the following method:
public static <T> List<T> randomList(List<T> l1, List<T> l2) {
return Math.random() < 0.5 ? l1 : l2;
}
致电:
randomList(new ArrayList<String>(), new ArrayList<Integer>()); // Does not Compile
如果这些ArrayList参数也被转换为对象,为什么这次会给我一个错误?
If those ArrayList Parameters are also getting upcasted to Object, why does it give me an error this time?
推荐答案
T
推断为Object
,并且两个参数都隐含地被抛弃.
T
is inferred to be Object
, and both arguments are getting implicitly upcast.
因此,代码等同于:
Main.<Object>random((Object)"string1", (Object)new Integer(10));
更令人惊讶的是,以下编译:
What may be even more surprising is that the following compiles:
random("string1", 10);
第二个参数将自动装箱到Integer
中,然后两个参数都被转换为Object
.
The second argument is getting auto-boxed into an Integer
, and then both arguments are getting upcast to Object
.
这篇关于为什么这个通用的Java方法接受两个不同类型的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!