簡體   English   中英

ArrayList無法使用(String [])list.toArray()轉換為String數組。 為什么?

[英]ArrayList fail to convert to a String array using (String[])list.toArray(). Why?

為什么以下代碼無法執行,盡管它不會從IDE檢測到錯誤。 它會編譯好。

 ArrayList<String> a = new ArrayList<String>();
    a.add("one");
    a.add("two");
    a.add("three");
    String [] b = (String[])a.toArray();
    for(int i =0;i<b.length;++i){
        System.out.println(b[i]);
    }

但它會給出以下錯誤。

嵌套異常是java.lang.ClassCastException:[Ljava.lang.Object; 無法轉換為[Ljava.lang.String;

有人能說清楚嗎? 之前已經提出過同樣的問題,並提供了一些解決方案。 但是對這個問題的明確解釋將非常感激。

你應該這樣做:

String[] b = new String[a.size()];
a.toArray(b);

您收到錯誤是因為toArray()返回Object[]而這不能轉換為String[]

你需要提到數組的類型,否則默認情況下, toArray()會返回一個Object數組,它不能簡單地轉換為String[] 如果指定了類型,則會調用重載的toArray(T[]) ,返回作為參數提到的數組類型。

String [] b = a.toArray(new String[]{});

a.toArray()正在創建一個Object[]而不是String[] ,因此類型轉換失敗了。

 String[] b = a.toArray(new String[a.size()]);

有關List.toArray的兩個重載,請參閱javadoc

看看JavaDoctoArray()返回一個Object[]數組,該數組不能向下轉換為String[]

你需要這個方法 - 原因是泛型在運行時被擦除,所以JVM不會知道你的ArrayList曾經是包含String的那個:

String [] b = a.toArray( new String[] {} );

干杯,

(現在/將來可能會有所幫助的東西。)

從1.5開始你就可以這樣做:

for(String output : a) { // Loops through each a (which is a String)
 System.out.println(output); // As it is a String list we can just print it
}

這更具可讀性,可能會派上用場。

輸出:

one
two
three

暫無
暫無

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

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