一 . list.clear()底層源碼實現
在使用list 結合的時候習慣了 list=null ;在創建這樣的方式,但是發現使用list的clear 方法很不錯,尤其是有大量循環的時候
1、list 接口 的ArrayList 類的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 方式都是將里面的所有元素都釋放了並且清空里面的屬性 ,這樣我們就不用在釋放 創建新對象來保存內容而是可以直接將現有的集合制空再次使用。
二. list.clear()與list = null 區別
java中list集合通過clear()方法清空,只會將list中的對象變成垃圾回收清空,但是list對象還是存在。
但是通過list=null后,不僅列表中的對象變成了垃圾,為列表分配的空間也會回收,什么都不做與賦值NULL一樣,說明直到程序結束也用不上列表list了,它自然就成為垃圾了.clear()只是清除了對象的引用,使那些對象成為垃圾.