Java List集合的clear方法

在使用list 结合的时候习惯了 list=null ;在创建这样的方式,但是发现使用list的clear 方法很不错,尤其是有大量循环的时候

1、list 接口  的ArrayList 类的clear() 方法源码如下:

 

[java]  view plain  copy
 
 print ?
  1. /** 
  2.      * Removes all of the elements from this list.  The list will 
  3.      * be empty after this call returns. 
  4.      */  
  5.     public void clear() {  
  6.         modCount++;  
  7.   
  8.         // Let gc do its work  
  9.         for (int i = 0; i < size; i++)  
  10.             elementData[i] = null;  
  11.   
  12.         size = 0;  
  13.     }  


我们从中可以发现就是将list集合中的所有对象都释放了,而且集合也都空了,所以我们没必要多次创建list 集合而只需要调用一下 clear() 方法就可以了。

 

 

2、list 接口  的LinkedList类的clear() 方法源码如下:

 

[java]  view plain  copy
 
 print ?
  1. public void clear() {  
  2.        // Clearing all of the links between nodes is "unnecessary", but:  
  3.        // - helps a generational GC if the discarded nodes inhabit  
  4.        //   more than one generation  
  5.        // - is sure to free memory even if there is a reachable Iterator  
  6.        for (Node<E> x = first; x != null; ) {  
  7.            Node<E> next = x.next;  
  8.            x.item = null;  
  9.            x.next = null;  
  10.            x.prev = null;  
  11.            x = next;  
  12.        }  
  13.        first = last = null;  
  14.        size = 0;  
  15.        modCount++;  
  16.    }  

 

 

从上面我们可以看到,不管是哪个实现类的clear 方式都是将里面的所有元素都释放了并且清空里面的属性  ,这样我们就不用再释放 创建新对象来保存内容而是可以直接将现有的集合制空再次使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值