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

问题描述

我无法理解以下文章:



下,

作者声明,

我无法理解它说$的部分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,

the author states,

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泛型协方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 04:41