0

谁能告诉我这段代码有什么错误?

public class Node<T> {
    private int degree;
    @SuppressWarnings("unchecked")
    T[] keys ;
    Node<T>[] children;
    Node(int degree) {
        System.out.println(degree);
        this.degree = degree;
        @SuppressWarnings("unchecked")
        Node<T>[] children = (Node<T>[])new Object[degree * 2];
        @SuppressWarnings("unchecked")
        T[] keys       = (T[])new Object[(degree * 2) - 1];
     }

     public static void main(String[] s) {
        Node<Integer> a = new Node<Integer>(5);
     }
}

基本上我想要一种自引用类型的东西,一个对象存储它自己的对象数组。我收到此错误

线程“main”中的异常 java.lang.ClassCastException: [Ljava.lang.Object; 不能转换为 [Tree.Node;

树是我的包名。

4

4 回答 4

2

而不是你的孩子和键的数组,使用List<Node<T>>and List<T>(和ArrayList作为实现)。通过这种方式,您可以隐藏ArrayList类中数组创建和强制转换的复杂性。(它也使用Object[],但仅转换 onget()和类似的方法,而不是尝试使用通用数组)。

或者,因为它看起来你无论如何都在创建一种映射,所以使用 aMap<T, Node<T>>作为你的键和节点(虽然你没有索引访问)。

于 2011-02-16T19:51:30.913 回答
2

您不能创建类型化数组。你必须这样做:

Node<T>[] children = new Node[degree * 2];

并处理数组无类型的事实:(

于 2011-02-16T19:34:07.247 回答
1

你不能做这个:

Node<T>[] children = (Node<T>[])new Object[degree * 2];

在这里,您正在创建一个 Object 数组,而 Object 不是 Node。您应该改为创建节点数组,即

Node<T>[] children = new Node[degree * 2];

您的代码中有两次相同的错误。

于 2011-02-16T19:35:24.243 回答
0

您不能将对象强制转换为节点:

Node<T>[] children = (Node<T>[])new Object[degree * 2];

要么您以错误的方式思考它:“任何对象都可以是一个节点”,而唯一正确的是“每个节点都是一个对象”,或者您习惯于 C++ 或类似的东西,您可以在其中强制转换指向任何其他指针的 void 指针。

此外,您不能拥有泛型类型的数组。例如,您必须创建一个包装器类型。StringNode extends Node<String>为了将它们存储在数组中。

例如,这个片段编译得很好:

class Node<T> {
}

class StringNode extends Node<String> {
}

public class Test {
    public void method() {
        Node<String>[] children = new StringNode[5];
    }
}
于 2011-02-16T19:32:09.620 回答