List集合的clear方法
阿新 • • 發佈:2019-01-01
在使用list 結合的時候習慣了 list=null ;在建立這樣的方式,但是發現使用list的clear 方法很不錯,尤其是有大量迴圈的時候
1、list 介面 的ArrayList 類的clear() 方法原始碼如下:
/** * Removes all of the elements from this list. The list will * be empty after this call returns. */ public void clear() { modCount++; // Let gc do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; }
我們從中可以發現就是將list集合中的所有物件都釋放了,而且集合也都空了,所以我們沒必要多次建立list 集合而只需要呼叫一下 clear() 方法就可以了。
2、list 介面 的LinkedList類的clear() 方法原始碼如下:
public void clear() { // Clearing all of the links between nodes is "unnecessary", but: // - helps a generational GC if the discarded nodes inhabit // more than one generation // - is sure to free memory even if there is a reachable Iterator for (Node<E> x = first; x != null; ) { Node<E> next = x.next; x.item = null; x.next = null; x.prev = null; x = next; } first = last = null; size = 0; modCount++; }
從上面我們可以看到,不管是哪個實現類的clear 方式都是將裡面的所有元素都釋放了並且清空裡面的屬性 ,這樣我們就不用在釋放 建立新物件來儲存內容而是可以直接將現有的集合制空再次使用。