java.lang.Object;无法转换为[Ljava.lang.Integer;位于com.java.Test.Test.main(Test.java:16) 公共类测试{ 公共静态void main(字符串[]args){ System.out.println(新的CountingGenerator.String(12.next()); 列表=新的ArrayList(); 添加(新整数(1)); 添加(新整数(2)); 整数[]c={1,3,3}; //引发异常: c=(整数[])list.toArray(); } }

java.lang.Object;无法转换为[Ljava.lang.Integer;位于com.java.Test.Test.main(Test.java:16) 公共类测试{ 公共静态void main(字符串[]args){ System.out.println(新的CountingGenerator.String(12.next()); 列表=新的ArrayList(); 添加(新整数(1)); 添加(新整数(2)); 整数[]c={1,3,3}; //引发异常: c=(整数[])list.toArray(); } },java,Java,我想知道为什么会发生这种情况?Integer是Object的子类,所以应该可以改为!请深入回答我!我想知道为什么?原理是什么?更改行 public class Test { public static void main(String[] args) { System.out.println(new CountingGenerator.String(12).next()); List<Integer> list=new ArrayList&l

我想知道为什么会发生这种情况?Integer是Object的子类,所以应该可以改为!请深入回答我!我想知道为什么?原理是什么?

更改行

public class Test {

    public static void main(String[] args) {
        System.out.println(new CountingGenerator.String(12).next());
        List<Integer> list=new ArrayList<Integer>();
        list.add(new Integer(1));
        list.add(new Integer(2));

        Integer[] c = {1,3,3};
        //throw an exception:
        c = (Integer[]) list.toArray();
    }
}

在您的
列表中,toArray();
返回
对象[]
,JVM不知道如何盲目地将
对象[]
向下转换为
整数[]

c= list.toArray(c); // add c as parameter
public Object[]toArray()//返回对象类型数组
public T[]toArray(T[]a)//返回包含此集合中所有元素的数组;返回数组的运行时类型是指定数组的运行时类型

List List=new ArrayList();为什么“List.toArray()”是一个对象数组???您可能想看看这个链接,没有自动递归转换到类型a到类型B的数组。您必须手动或使用专用方法,如“Arrays.Copyof()”。您不能将整数列表视为对象列表“谢谢汤姆!谢谢托尼!你不能把一个整数列表当作一个对象列表!
c= list.toArray(c); // add c as parameter
public Object[] toArray()      //return Object type array
public <T> T[] toArray(T[] a) //Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array