簡體   English   中英

java.lang.Object繼承; 無法轉換為[Ljava.lang.Integer;在com.java.Test.Test.main(Test.java:16)

[英]java.lang.Object; cannot be cast to [Ljava.lang.Integer;at com.java.Test.Test.main(Test.java:16)

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

我想知道為什么會這樣? Integer是Object的子類,所以它應該是OK! 請深深地回答我! 我想知道為什么? 原理是什么?

改變線

 c=(Integer[]) list.toArray();

c= list.toArray(c); // add c as parameter

在你的list.toArray(); 返回Object[]並且JVM不知道如何盲目地將Object[]向下轉換為Integer[]

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

Java Docs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM