考虑以下列表:
List<? extends Exception> errLst = new ArrayList<>();
现在考虑这个对象:
IOException err = new IOException();
为什么我不能将 err 添加到 errLst,即使 err 是 Exception 的一个实例?据我所知,errLst 应该接受任何继承自 Exception 类(上限)的对象。
我还注意到以下代码与之前的代码相反,可以正常工作:
List<? super Exception> errLst2 = new ArrayList<>();
errLst.add(new IOException());
但是,据我所知,errLst2 应该只接受 Exception 继承自(下界)的类型。
最佳答案
这就是泛型的本质。
errList
包含某种特定类型,它是Exception
或其子类型。但不知道该特定类型是否实际上是 IOException
,例如,它也可能是 RuntimeException
。
这就是编译器不允许您添加 IOException
的原因。
何时使用通配符?
如果您想表示类型参数实际上并不重要,则可以使用通配符。例如,如果我要编写一个弹出某个列表的最后一个元素的方法,那么元素的类型实际上并不重要。
public static void popOffLastElement(List<?> list) {
if (list.size() > 0) {
int lastIndex = list.size() - 1;
list.remove(lastIndex);
}
}
我们需要通配符吗?
好吧,我们可以使用类型参数实现相同的目的:
public static <T> void popOffLastElement(List<T> list) {
if (list.size() > 0) {
int lastIndex = list.size() - 1;
list.remove(lastIndex);
}
}
所以严格来说,通配符不是必需的。
关于java - 为什么不能将 IOException() 对象添加到 "? extends Exception"的集合中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57035055/