1.public Object[] toArray() {   
  • Object[] result = new Object[size];   
  • System.arraycopy(elementData, 0, result, 0, size);   
  • return result;   
  •    }  
  •  


    String[] to = (String[])to_list.toArray();   

    ArrayList.toArray()返回的Object[]是其創建類型,downcast到其子類String[] 當然是非法的cast,所以會報錯。


    2.
    1. public Object[] toArray(Object a[]) {   
    2.     if (a.length < size)   
    3.         a = (Object[])java.lang.reflect.Array.newInstance(   
    4.                             a.getClass().getComponentType(), size);   
    5.     System.arraycopy(elementData, 0, a, 0, size);   
    6.   
    7.     if (a.length > size)   
    8.         a[size] = null;   
    9.   
    10.     return a;   
    11. }  

    它是根據你傳進來的那個數組的元素類型進行創建,所以就不會有類型不匹配的問題。

    無參數的實現中,它是按照Object[]進行創建,當然就會存在一個類型匹配的問題了。



    java sdk doc 上講:
     
          public Object[] toArray(Object[] a)

          a--the array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same  runtime type is allocated for this purpose.

          如果這個數組a足夠大,就會把數據全放進去,返回的數組也是指向這個數組,(數組多余的空間存儲的是null對象);要是不夠大,就申請一個跟參數同樣類型的數組,把值放進去,然后返回。



     



    ------君臨天下,舍我其誰------