2

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


}
1
  • @PeterBruins Realized that, thanks. Commented Jun 12, 2018 at 10:28

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.