开发者

Class Cast Exception in Java: cannot be cast

Could anyone tell me what is the error in this code?

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[] ke开发者_Go百科ys       = (T[])new Object[(degree * 2) - 1];
     }

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

Basically I want a self referential kind of a thing that an object stores an array of its own objects. I am getting this error

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Tree.Node;

Tree is my package name.


You can't make a Typed array. You have to do this:

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

And deal with the fact that arrays are untyped :(


Instead of arrays for your children and keys, use List<Node<T>> and List<T> (and ArrayList as the implementation). This way you hide away the complexity of the array creation and casting inside the ArrayList class. (It uses an Object[], too, but only converts on get() and similar methods instead of trying to have a generic array).

Or, since it looks you are creating kind of a map anyways, use a Map<T, Node<T>> for your keys and nodes (you have no index-access then, though).


You cannot do this:

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

Here you are creating an Object array and an Object is not a Node. You should be creating a Node array instead, i.e.

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

You have this same error twice in your code.


You can't cast an Object to a Node:

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

Either you're thinking of it the wrong way: "Any Object could be a Node" when the only thing that is true is "Every Node is an Object", or, you're used to C++ or similar in which you may cast a void pointer to any other pointer.

Furthermore, you can't have arrays of generic types. You'll have to for instance create a wrapper type, say. StringNode extends Node<String> in order to store them in an array.

This snippet, for instance, compiles just fine:

class Node<T> {
}

class StringNode extends Node<String> {
}

public class Test {
    public void method() {
        Node<String>[] children = new StringNode[5];
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜