投射对象数组

时间:2014-02-09 18:29:37

标签: java arrays object casting

我是java的新手,我为某些public class MergeSort<Item>

进行了演员表
Integer N = Integer.valueOf(StdIn.readString());   
MergeSort<Integer>[] input = (MergeSort<Integer>[]) new Object[N];

我得到了这个:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LMergeSort;

1 个答案:

答案 0 :(得分:1)

这不起作用,因为您正在尝试将数组转换为其类的数组子类型。你会从代码中得到同样的错误:

Integer[] input = (Integer[]) new Object[N];

为什么这不起作用?因为原始数组设置为允许其中的任何对象。它是不允许的,因为从数组中检索元素(在数组大小内)应该始终有效。该错误阻止了以下类型的事情:

Object[] arr = new Object[1];
arr[0] = "Hello, world!";
Integer[] input = (Integer[]) arr; //Runtime error here
Integer i = input[0]; //This operation is supposed to never throw an error, but it would if one hadn't been thrown earlier.

&#34;但是在我的代码中,数组会立即转换为我的Object子类型,并且永远不会接收任何其他类型的对象。&#34;不是这样!如果允许您的演员表,则以下内容有效:

MergeSort[] input = (MergeSort[]) new Object[N]; //Runtime error here
Object[] arr = input; //Casting to supertype is valid; inserting wrong elements is checked by ArrayStoreException
arr[0] = "Not a MergeSort!"; //Valid because array was originally constructed as an Object[]
MergeSort m = input[0]; //Supposed to always work, but can't possibly work.

&#34;等等,你为什么要从我的MergeSort中取出?&#34;见this question。简而言之,在运行时,MergeSort与MergeSort和其他所有类型的MergeSort无法区分,因此,再次阻止您尝试从数组中检索一类对象,而不是接收另一类,则无法在您的数组中指定泛型数组创建。相反,建立一个合同,数组中的所有元素必须是MergeSort,并将您的检索从数组转换为MergeSort。对于非局部变量,您可以这样做:

private MergeSort[] input = ...;
public MergeSort<Integer> getMergeSort(int pos) {
    return (MergeSort<Integer>) input[pos]; //Compiler warning here because it could throw an error if the contract of setMergeSort(...) is not followed.
}
public void setMergeSort(int pos, MergeSort<Integer> mergeSort) {
    input[pos] = mergeSort;
}