Java泛型返回数组 [英] java generics return an array
问题描述
编辑:我没有看到其他的问题如何回答我的。我已经有一个明确的CAST(E []),它的另一个问题笔者所没有的。
我也尝试过类似SEQ1 =(整数[])iw.result();但这并不能工作。
edit: I don't see how the other question answers mine. I already have an explicit cast (E[]) which the author of the other question doesn't have. I also tried something like seq1 = (Integer[]) iw.result(); but that doesn't work either.
我有以下的code:
public class Something<E extends Comparable<E>> {
E[] seq;
public Something() {
seq = (E[]) new Object[100];
}
public E[] result() {
return sequence;
}
public static void main(String[] args) {
Something<Integer> iw = new Something<Integer>();
Integer[] seq1 = new Integer[100];
seq1 = iw.result();
}}
我得到的方式的errormessage的:[对象不能转换为[可比
I get an errormessage in the way of: [Object can't be cast to [Comparable
所以我改变的东西 - 构造器:
So I change the Something-Constructor to:
seq = (E[]) new Comparable[100];
现在我得到的方式的errormessage的:[可比不能转换为[整数
Now I get an errormessage in the way of: [Comparable can't be cast to [Integer
有没有什么办法,使上述code的工作?我知道我会过得更好使用集合在这里,但我只是好奇,这有什么错我的code。
Is there any way to make the above code work? I know I would be better off working with Collections here, but I'm just curious what's wrong with my code.
推荐答案
一对夫妇在这里的问题。
A couple of issues here.
首先,这不是一个无界的泛型参数,这是有一个必然的可比&LT; E&GT;
连接到它
First, that's not an unbounded generic parameter, that's got a bound of Comparable<E>
attached to it.
在类型擦除,用类声明为:
During type erasure, with your class declared as:
public class Something<E extends Comparable<E>> {
E[] seq;
}
... 电子
势必可比
。
public class Something {
Comparable[] seq;
}
的这的是,为什么你的铸件行不通的,因为一个对象
不是可比
。你想用新可比
代替。
This is why your casting isn't going to work, since an Object
is not a Comparable
. You would want to use new Comparable
instead.
public class Something<E extends Comparable<E>> {
E[] seq;
public Something() {
seq = (E[]) new Comparable[100];
}
}
现在,Java是和的应的突破的最后两个语句。
Now, Java is and should break on the last two statements.
Integer[] seq1 = new Integer[100];
seq1 = iw.result();
iw.result()
势必可比[]
,而不是整数[ ]
。 A 可比[]
永远不能成为一个整数[]
。
iw.result()
is bound to Comparable[]
, not Integer[]
. A Comparable[]
can never become an Integer[]
.
您可以做到这一点,而不是避开了 ClassCastException异常
而不是:
You can do this instead to eschew the ClassCastException
instead:
Comparable[] seq1 = new Integer[100];
因为一个整数
这将工作是可比
。这是由于这一事实,即数组是协变的(也就是说,一个整数[]
是一个亚型可比[]
)。
This will work since an Integer
is Comparable
. This is due to the fact that arrays are covariant (that is to say, an Integer[]
is a subtype of a Comparable[]
).
这篇关于Java泛型返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!