list.clear()與list = null 區別

一 . list.clear()底層源碼實現

在使用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 方式都是將裏面的所有元素都釋放了並且清空裏面的屬性  ,這樣我們就不用在釋放 創建新對象來保存內容而是可以直接將現有的集合制空再次使用。

 

二. list.clear()與list = null 區別

java中list集合通過clear()方法清空,只會將list中的對象變成垃圾回收清空,但是list對象還是存在。 
但是通過list=null後,不僅列表中的對象變成了垃圾,爲列表分配的空間也會回收,什麼都不做與賦值NULL一樣,說明直到程序結束也用不上列表list了,它自然就成爲垃圾了.clear()只是清除了對象的引用,使那些對象成爲垃圾. 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章