---
title: "Java List集合的clear方法"
author: "windpoplar"
date: "2017-02-25T21:16:06Z"
tags: []
categories: ["编程语言"]
slug: "java-list-clear"
draft: false
lastmod: "2017-02-25T21:16:06Z"
id: 2359104
url: "https://windpoplar.iteye.com/blog/2359104"
---

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

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

 

**\[java]** [view plain](http://blog.csdn.net/qh_java/article/details/50098697 "view plain") [copy](http://blog.csdn.net/qh_java/article/details/50098697 "copy")

 

 [print](http://blog.csdn.net/qh_java/article/details/50098697 "print")[?](http://blog.csdn.net/qh_java/article/details/50098697 "?")

01. /\**
02. * Removes all of the elements from this list.  The list will
03. * be empty after this call returns.
04. \*/
05. public void clear() {
06. modCount++;
07. // Let gc do its work
08. for (int i = 0; i &lt; size; i++)
09. elementData\[i] = null;
10. size = 0;
11. }

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

 

 

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

 

**\[java]** [view plain](http://blog.csdn.net/qh_java/article/details/50098697 "view plain") [copy](http://blog.csdn.net/qh_java/article/details/50098697 "copy")

 

 [print](http://blog.csdn.net/qh_java/article/details/50098697 "print")[?](http://blog.csdn.net/qh_java/article/details/50098697 "?")

01. public void clear() {
02. // Clearing all of the links between nodes is "unnecessary", but:
03. // - helps a generational GC if the discarded nodes inhabit
04. //   more than one generation
05. // - is sure to free memory even if there is a reachable Iterator
06. for (Node&lt;E&gt; x = first; x != null; ) {
07. Node&lt;E&gt; next = x.next;
08. x.item = null;
09. x.next = null;
10. x.prev = null;
11. x = next;
12. }
13. first = last = null;
14. size = 0;
15. modCount++;
16. }

 

 

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