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