user506710
user506710

Reputation:

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[] keys       = (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.

Upvotes: 0

Views: 8638

Answers (4)

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74800

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).

Upvotes: 2

aioobe
aioobe

Reputation: 421310

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];
    }
}

Upvotes: 0

brent777
brent777

Reputation: 3379

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.

Upvotes: 1

corsiKa
corsiKa

Reputation: 82599

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 :(

Upvotes: 2

Related Questions