java 泛型数组和 Classcastexception
java generic array and Classcast exception
我声明了 BinaryTree 如下:
public class BinaryTree<T extends Comparable<T>> {}
但是当我打电话给
Character[] actual = binaryTreeChar.preOrderTraversal(root, Character[].class);
它正在抛出如下异常。
java.lang.ClassCastException: [[Ljava.lang.Character; cannot be cast
to [Ljava.lang.Comparable;
有没有更好的方法来处理这些情况?
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;
}
}
应该是:
public T[] preOrderTraversal(BinaryNode<T> root, Class<T> clazz)
并且:
Character[] actual = binaryTreeChar.preOrderTraversal(root, Character.class);
就像现在一样,您正在创建 Character[][]
的实例(即二维数组)。
传给Array.newInstance
的Class
是数组的组件类型,不是数组类型
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
我声明了 BinaryTree 如下:
public class BinaryTree<T extends Comparable<T>> {}
但是当我打电话给
Character[] actual = binaryTreeChar.preOrderTraversal(root, Character[].class);
它正在抛出如下异常。
java.lang.ClassCastException: [[Ljava.lang.Character; cannot be cast to [Ljava.lang.Comparable;
有没有更好的方法来处理这些情况?
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;
}
}
应该是:
public T[] preOrderTraversal(BinaryNode<T> root, Class<T> clazz)
并且:
Character[] actual = binaryTreeChar.preOrderTraversal(root, Character.class);
就像现在一样,您正在创建 Character[][]
的实例(即二维数组)。
传给Array.newInstance
的Class
是数组的组件类型,不是数组类型
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