我不确定为什么以下代码中的最后一个语句是非法的.Integer应该是一个子类型?,为什么我不能分配给它b?
List<String> a = new ArrayList<String>();
a.add("foo");
// b is a List of anything
List<?> b = a;
// retrieve the first element
Object c = b.get(0);
// This is legal, because we can guarantee
// that the return type "?" is a subtype of Object
// Add an Integer to b.
b.add(new Integer (1));
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 11
关键是b指某种类型的列表,但编译器不知道该类型是什么,因此它不知道添加一个类型是否有效Integer.同样也是一件好事,给出你的例子 - 你要添加一个Integer最初创建的对象来保存一个字符串列表.当然,在Java中执行时会丢失该信息 - 但编译器会尽量保证您的安全.
见Java泛型常见问题解答了很多的更多信息.
| 归档时间: |
|
| 查看次数: |
338 次 |
| 最近记录: |