考虑这段代码:
public <T> List<T> meth(List<?> type)
{
System.out.println(type); // 1
return new ArrayList<String>(); // 2
}
它在第 2 行没有编译,说明 List 是必需的。
现在,如果更改为:
public <T> List<?> meth(List<T> type)
{
System.out.println(type); // 1
return new ArrayList<String>(); // 2
}
它确实可以编译。为什么?我认为用 T 声明泛型类型和使用通配符之间的区别在于,使用通配符时,无法向集合添加新元素。为什么会<?>
允许返回 List 的子类型吗?我在这里遗漏了一些东西,明确的规则是什么以及如何应用它?
最佳答案
区别在于返回类型声明。 List<String>
不是 List<T>
的子类型,但它是 List<?>
的子类型.
List<?>
对其类型变量不做任何假设,因此以下语句是有效的:
List<?> l0 = new ArrayList<String>();
List<?> l1 = new ArrayList<Object>();
List<? extends Number> ltemp = null;
List<?> l2 = ltemp;
List<T>
当您将其声明为 List<String>
时,假设类型参数将在客户端上下文中解析(例如类型使用)。或List<Object>
。在方法体内,您也不能对其做出任何假设。
关于Java泛型方法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1149964/