Sum*_*mit 4 java bounded-wildcard
List<? super IOException>表示列表可以包含IOException对象或任何属于super类的对象IOException。那么为什么下面的第2行不编译?
同样在第3行FileNotFoundException中也不是的super类IOException。那为什么编译呢?
List<? super IOException> myList = new ArrayList<Exception>();
myList.add(new Exception()); //Line 2 This line do not compile
myList.add(new FileNotFoundException()); //Line 3 This compiles
Run Code Online (Sandbox Code Playgroud)
通配符下限指定type参数的下限,而不是的可接受类型List。类型参数可以和一样具体IOException,但可以像我们得到的一样通用Object。
添加an时Exception,该项目的类型作为项目太笼统,因为type参数可能太具体了-它可能是IOException。编译器不允许您向Exception可能只包含IOExceptions的内容添加,因此会生成错误。
不会发生这种情况FileNotFoundException,因为无论type参数有多具体,它都不会比IOException(下界)更具体,因此a FileNotFoundException,它是的子类IOException在所有情况下都是合法的,因此编译器允许它。
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |