编辑:我不明白其他问题如何回答我的问题。我已经有一个明确的强制转换(E[]),而另一个问题的作者没有。 我还尝试了类似 seq1 = (Integer[]) iw.result(); 的方法但这也行不通。
我有以下代码:
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();
}}
我收到一条错误消息:[对象无法转换为 [Comparable
所以我将 Something-Constructor 更改为:
seq = (E[]) new Comparable[100];
现在我收到一条错误消息:[Comparable 无法转换为 [Integer
有什么办法可以让上面的代码工作起来吗?我知道在这里使用 Collections 会更好,但我只是好奇我的代码出了什么问题。
最佳答案
这里有几个问题。
首先,这不是一个无限的泛型参数,它的界限是 Comparable<E>
附在其上。
在类型删除期间,您的类声明为:
public class Something<E extends Comparable<E>> {
E[] seq;
}
... E
绑定(bind)到Comparable
.
public class Something {
Comparable[] seq;
}
这就是你的转换不起作用的原因,因为 Object
不是Comparable
。您可能想要使用 new Comparable
相反。
public class Something<E extends Comparable<E>> {
E[] seq;
public Something() {
seq = (E[]) new Comparable[100];
}
}
现在,Java 应该在最后两条语句上中断。
Integer[] seq1 = new Integer[100];
seq1 = iw.result();
iw.result()
绑定(bind)到Comparable[]
,不是Integer[]
。一个Comparable[]
永远不可能成为Integer[]
.
您可以这样做来避开 ClassCastException
相反:
Comparable[] seq1 = new Integer[100];
这将在Integer
之后起作用是 Comparable
。这是因为数组是协变的(也就是说, Integer[]
是 Comparable[]
的子类型)。
关于java泛型返回一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29078789/