Reputation:
I am trying to implement an array based tree where each node has a list of child nodes and I am getting an error that I need help fixing.
Error:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lassign2Trees.ArrayTreeNode;
at assign2Trees.ArrayTree.<init>(ArrayTree.java:15)
at assign2Trees.ArrayTree.main(ArrayTree.java:97
)
The error comes from here I believe:
ArrayTreeNode<E>[] tree = (ArrayTreeNode<E>[]) new Object[1];
Upvotes: 2
Views: 387
Reputation: 139961
ClassCastException: [Ljava.lang.Object; cannot be cast to [Lassign2Trees.ArrayTreeNode;
at assign2Trees.ArrayTree.<init>(ArrayTree.java:15)
refers to this line:
ArrayTreeNode<E>[] tree = (ArrayTreeNode<E>[]) new Object[1];
You cannot cast an Object[]
to any other type.
Even if this worked, you have another error immediately after this: arrays in Java are indexed starting at 0, not 1. To access the first element in an array, you would refer to tree[0]
.
Upvotes: 3