Reputation: 921
I had declared BinaryTree as below :
public class BinaryTree<T extends Comparable<T>> {}
But when I call
Character[] actual = binaryTreeChar.preOrderTraversal(root, Character[].class);
it is throwing exception as below.
java.lang.ClassCastException: [[Ljava.lang.Character; cannot be cast to [Ljava.lang.Comparable;
Is there any better way to deal these cases ?
public T[] preOrderTraversal(BinaryNode<T> root, Class<T[]> clazz) {
if (root == null)
return null;
T[] array = (T[]) Array.newInstance(clazz, count);
Stack<BinaryNode<T>> stack = new Stack<>();
stack.push(root);
int i = 0;
while (!stack.empty()) {
BinaryNode<T> next = stack.pop();
array[i++] = next.data;
if (next.right != null)
stack.push(next.right);
if (next.left != null)
stack.push(next.left);
}
return array;
}
}
Upvotes: 2
Views: 63
Reputation: 393771
It should be:
public T[] preOrderTraversal(BinaryNode<T> root, Class<T> clazz)
And:
Character[] actual = binaryTreeChar.preOrderTraversal(root, Character.class);
As it is now, you are creating an instance of a Character[][]
(i.e. a two dimensional array).
The Class
passed to Array.newInstance
is the component type of the array, not the array type.
Object java.lang.reflect.Array.newInstance(Class componentType, int length) throws NegativeArraySizeException
Creates a new array with the specified component type and length...
Parameters:
componentType the Class object representing the component type of the new array
length the length of the new array
Upvotes: 2