Java - ArratList-> toarray()方法詳解__Java

來源:互聯網
上載者:User

API:http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

ArrayList提供了一個將List轉為數組的一個非常方便的方法toArray。toArray有兩個重載的方法:
1.list.toArray();
2.list.toArray(T[] a); 對於第一個重載方法,是將list直接轉為Object[] 數組; 第二種方法是將list轉化為你所需要類型的數組,當然我們用的時候會轉化為與list內容相同的類型。

一般而言,我們都是這麼寫得:    ArrayList<String> list=new ArrayList<String>();        for (int i = 0; i < 10; i++) {            list.add(""+i);        }        String[] array= (String[]) list.toArray();ArrayList<String> list=new ArrayList<String>();        for (int i = 0; i < 10; i++) {            list.add(""+i);        }        String[] array= (String[]) list.toArray();
然而,運行出錯,這是為什麼呢? 錯誤提示如下:Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;Object[] 不可以轉化為String[];   需要進行每個元素的單獨轉換那麼正確的就應該是:    Object[] arr = list.toArray();    for (int i = 0; i < arr.length; i++) {         String e = (String) arr[i];         System.out.println(e);    }

由例題可見,第一個重載方法toArray()是不夠完善的,而第二個重載方法會顯得高效,實用~

下面我貼出兩種構造方法的實現過程,大家可以自行體會

public Object[] toArray(); {        Object[] result = new Object[size];        System.arraycopy(elementData, 0, result, 0, size);;        return result;    }    public Object[] toArray(Object a[]); {        if (a.length < size)            a = (Object[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);        System.arraycopy(elementData, 0, a, 0, size);;        if (a.length > size)            a[size] = null;  //@1        return a;    }
@1處,為何會置為null呢。:如果你遇到了類似的問題,你首先做的就是查看API注視,而不是冥思苦想~~API:[http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#toArray(T[])](http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#toArray%28T%5B%5D%29)     * <p>If the list fits in the specified array with room to spare     * (i.e., the array has more elements than the list), the element in     * the array immediately following the end of the collection is set to     * <tt>null</tt>.  (This is useful in determining the length of the     * list <i>only</i> if the caller knows that the list does not contain     * any null elements.)*/
這句話的意思是:僅 在調用者知道列表中不包含任何 null 元素時才能用此方法確定列表長度】,原來的那個list中沒有null元素,這樣它a[size] = null;賦值後,在確定list長度時才是有用的.如果之前的list當中有null元素,就沒辦法判斷哪個是真的長度了。
使用Demo:1).參數指定空數組,節省空間的String[] y = x.toArray(new String[0]);2).指定大數組參數浪費時間,採用反射機制String[] y = x.toArray(new String[100]);  //假設數組size大於1003).姑且認為最好的String[] y = x.toArray(new String[x.size()]); 

歡迎大家提出你的問題~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.