java泛型协方差 [英] java generics covariance
问题描述
我无法理解以下文章:
http ://www.ibm.com/developerworks/java/library/j-jtp01255.html
下,
泛型不是协变
作者声明,
因为ln是一个List,所以添加一个
浮点数似乎完全合法。但是
如果ln与li是别名,那么
会打破类型安全承诺
隐含在li -
的定义中,它是一个整数列表,它是
是为什么泛型不能是
协变。
我无法理解它说$的部分b $ b如果ln与li混淆。作者的意思是别名?(参考?)。引用行上面的代码片段似乎说明了在java中什么是非法的,而不是为什么。如果有人能够用一个例子来解释,那对我来说会非常有帮助。
在此先感谢。
列表< Integer> li = new ArrayList< Integer>();
列表<号码> ln = li; //非法
ln.add(new Float(3.1415));在Java中,Integer继承自Number (java.lang.Number)
$ b / code>,所以直观地说,任何一个Integer (java.lang.Integer)
也是一个数字,但是该文章指出的是,泛型它不会那样工作,因为考虑到这个例子,你最终可能会把float(这是一个Number)放到 List< Integer>
中,这是非法的,因为float不是一个整数。
结论:泛型不是协变的。
注意:我推荐您阅读 Effective Java(第2版)第5章:泛型。
I am having trouble understanding the following article:
http://www.ibm.com/developerworks/java/library/j-jtp01255.html
Under,
Generics are not covariant
the author states,
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.
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));
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.
Conclusion: Generics are not covariant.
Note: I recommend you read Effective Java (2nd Edition) Chapter 5: Generics.
这篇关于java泛型协方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!