报错代码:
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);