-1

In the Node Class constructor, I am trying to initialize childArray and dataArray which are objects based on Generic class themselves.

private class Node<type extends Comparable<type>> {
        public Node<type>[] childArray;
        public DataItem<type>[] dataArray;
        public int dataCount; //No. of data elements in the node
        public int childCount; //No. of child elements under it
        public Node<type> parent;
        private static final int ORDER = 4;

        public Node() {

            childArray = (Node<type>[]) new Object[ORDER];
            dataArray = (DataItem<type>[]) new Object[ORDER - 1];
            dataCount = 0;
            childCount = 0;
        }
}

I am getting the following error when I try to compile:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LTree234$Node;
    at Tree234$Node.<init>(Tree234.java:37)
    at Tree234.<init>(Tree234.java:149)
    at Tree234.main(Tree234.java:266)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

The complete code can be found at: https://gist.github.com/stirredo/2a40d48021a8b9e14959

How do I overcome this problem?

I know there are many questions with the exception found in my problem but I am not able to apply them to my problem.

stirredo
  • 1,792
  • 3
  • 16
  • 23

2 Answers2

1

You are attempting to cast an Object[] to a Node[] without the Object[] having ever been a Node[]. Presumably you put the cast on it because childArray = new Object[ORDER] was giving you incompatible types at compile time. Similarly, the ClassCastException is due to the two failing to resolve to a "compatible" state (at runtime).

So you want it to be childArray = new Node<T>[ORDER]; which is also not possible. In short, you should use some form of Collection

class Node<T extends Comparable<T>> {
  private Collection<Node<T>> children;
}
Community
  • 1
  • 1
Origineil
  • 3,048
  • 2
  • 10
  • 17
1
childArray = (Node<type>[])new Node[ORDER];

or

childArray = (Node<type>[])new Node<?>[ORDER];
newacct
  • 110,405
  • 27
  • 152
  • 217