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[]是其創(chuàng)建類型,downcast到其子類String[] 當(dāng)然是非法的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. }  

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

    無參數(shù)的實現(xiàn)中,它是按照Object[]進行創(chuàng)建,當(dāng)然就會存在一個類型匹配的問題了。



    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.

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



     



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