報錯代碼:
1 private void ArraytoList() { 2 // Array--->List 3 String[] strArray = new String[] { "aa", "bb" }; 4 List<String> list = new ArrayList<String>(Arrays.asList(strArray)); 5 list.add("cc"); 6 // List--->Array 7 String[] strArray2; 8 try { 9 strArray2 = (String[]) list.toArray(); 10 } catch (Exception e) { 11 Log.i("ToArray", "failure:" + e.getMessage()); 12 } 13 }
原因為list.toArray()返回的是Object類型,強制轉換的時候發生ClassCastException
修改代碼:
1 private void ArraytoList() 2 // Array--->List 3 String[] strArray = new String[] { "aa", "bb" }; 4 List<String> list = new ArrayList<String>(Arrays.asList(strArray)); 5 list.add("cc"); 6 // List--->Array 7 String[] strArray2 = null; 8 try { 9 strArray2 = list.toArray(new String[0]); 10 } catch (Exception e) { 11 Log.i("ToArray", "failure:" + e.getMessage()); 12 } 13 for (String element : strArray2) { 14 Log.i("ToArray", "strArray2:" + element); 15 } 16 }
以下兩段代碼效果一致:
1 strArray2 = list.toArray(new String[0]);
2 strArray2 = new String[list.size()]; 3 strArray2 = list.toArray(strArray2);
不帶參數的toArray方法,是構造的一個Object數組,然后進行數據拷貝,此時進行轉型就會產生ClassCastException,而帶參數的toArray方法,則是根據參數數組的類型,構造了一個對應類型的,長度跟ArrayList的size一致的空數組,雖然方法本身還是以 Object數組的形式返回結果,不過由於構造數組使用的ComponentType跟需要轉型的ComponentType一致,就不會產生轉型異常。
以后使用toArray方法可以參考以下方式:
1 1. Long[] l = new Long[<total size>]; 2 list.toArray(l); 3 4 2. Long[] l = (Long[]) list.toArray(new Long[0]); 5 6 3. Long[] a = new Long[<total size>]; 7 Long[] l = (Long[]) list.toArray(a);