【发布时间】:2012-12-06 04:12:39
【问题描述】:
此方法将获取两个相同类型的对象并随机返回其中一个对象:
public static <T> T random(T o1, T o2)
{
return Math.random() < 0.5 ? o1 : o2;
}
现在,为什么编译器会接受两个不同类型的参数?
random("string1", new Integer(10)); // Compiles without errors
编辑: 现在我知道这两个参数都被隐式向上转换了,我想知道为什么编译器确实在调用以下方法时会抱怨:
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 参数也被向上转换为 Object,为什么这次它会给我一个错误?
【问题讨论】:
-
因为他们都是
Objects。 -
@user1914126.. 就目前而言,您的代码不应编译。您在
Integer(10)之前缺少new。 -
是的,如果你想让编译器抱怨你必须告诉它当你调用方法时 T 应该是什么,例如
MyClass.<String>random("string1", new Integer(10));。那将是一个错误。
标签: java generics methods parameters