List集合的clear方法

 

一 . 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;  

扫描二维码关注公众号,回复: 79742 查看本文章

        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()只是清除了对象的引用,使那些对象成为垃圾. 

 

猜你喜欢

转载自www.cnblogs.com/shoshana-kong/p/8962485.html