【发布时间】:2019-05-12 15:11:42
【问题描述】:
我正在尝试创建嵌套类Key 的数组,它使用主类BTree 中的类型变量/参数,但我无法在运行时摆脱ClassCastException。我不太擅长 Java 中的泛型,如果有人告诉我问题是什么以及如何解决它,我将不胜感激。
public class BTree<T extends Comparable<T>, V> {
//...
private class Node {
public int n;
public boolean isLeaf = false;
public Key[] keys = (Key[]) new Comparable[2 * MIN_DEGREE - 1]; //ClassCastException
public Node[] children = (Node[]) new Object[2 * MIN_DEGREE];
}
private class Key implements Comparable<Key> {
public T key;
public V val;
public Key(T key, V val) {
this.key = key;
this.val = val;
}
public boolean lessThan(Key that) {
return this.key.compareTo(that.key) < 0;
}
public boolean greaterThan(Key that) {
return this.key.compareTo(that.key) > 0;
}
@Override
public int compareTo(Key that) {
if (this.lessThan(that)) return -1;
if (this.greaterThan(that)) return 1;
return 0;
}
}
//....
}
编辑:
我还尝试将Object 数组转换为Key 数组,它也会抛出ClassCastException:
public Key[] keys = (Key[]) new Object[2 * MIN_DEGREE - 1];
当我创建 Key 数组而不进行强制转换时,它会在编译时出现 Generic array creation 错误:
public Key[] keys = new Key[2 * MIN_DEGREE - 1];
【问题讨论】:
-
您正在尝试将 Comparables 数组转换为 Keys 数组。这就像将一系列哺乳动物(骆驼、马和猫)转换成一系列狗。为什么要这样做?创建一个 Key 数组和一个 Node 数组。
-
@RealSkeptic 我在创建 Key
new Key[size]的数组时出现通用数组创建错误 -
是的,因为泛型和数组不能混用。实际上,我不确定您要在这里做什么,但是您为什么不使用列表?
-
通用数组创建错误可以通过创建对象数组并将其转换为请求的通用类型来解决。例如T[] myArray = (T[]) new Object[10];还要检查有关此的其他讨论,例如stackoverflow.com/questions/17831896/…
-
@RealSkeptic 我正在实现 CLRS 书中的 B-trees,它使用数组,而且我认为使用列表可能会影响搜索和插入等操作的运行时间(尽管不确定)。