java泛型协方差 [英] java generics covariance

查看:30
本文介绍了java泛型协方差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解以下文章:http://www.ibm.com/developerworks/java/library/j-jtp01255.html

下,

泛型不是协变的

作者声明,

因为ln是一个List,添加一个浮动到它似乎完全合法.但如果 ln 别名为 li,那么它会破坏类型安全承诺隐含在 li 的定义中——它是一个整数列表,其中这就是为什么不能是泛型类型协变.

Because ln is a List, adding a Float to it seems perfectly legal. But if ln were aliased with li, then it would break the type-safety promise implicit in the definition of li -- that it is a list of integers, which is why generic types cannot be covariant.

我无法理解它所说的部分如果 ln 是 li 的别名".作者所说的别名是什么意思?(参考?).引用行上方的代码片段似乎说明了在 java 中什么是非法的,而不是为什么.如果有人可以用一个例子来解释,那对我会很有帮助.提前致谢.

I can't understand the part where it says "if ln were aliased with li". What does the author means by alias?(reference?). The code snippet above the quoted line seems to illustrate WHAT is illegal in java and not WHY. It would be very helpful to me if somebody could explain with an example. Thanks in advance.

推荐答案

List<Integer> li = new ArrayList<Integer>();
List<Number> ln = li; // illegal
ln.add(new Float(3.1415));

在 Java 中,Integer 继承自 Number(java.lang.Number),所以直观上,任何是 Integer(java.lang.Integer) 的东西也是一个数字,但那篇文章指出,泛型不能那样工作,因为考虑到该示例,您最终可能会将一个浮点数(它是一个数字)放入 List,这是非法的,因为浮点数不是整数.

In Java, Integer inherits from Number(java.lang.Number), so intuitively, anything that is an Integer(java.lang.Integer) is also a number, but what that article points out is that with generics it does not work that way, because considering that example, you could end up putting a float (which is a Number) into a List<Integer>, which is illegal because a float is not an integer.

结论:泛型不是协变的.

注意:我建议您阅读Effective Java(第二版)第 5 章:泛型.

这篇关于java泛型协方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆