在使用list 结合的时候习惯了 list=null ;在建立这样的方式,可是发现使用list的clear 方法很不错,尤为是有大量循环的时候html
以下:java
以下:
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 方式都是将里面的全部元素都释放了而且清空里面的属性 ,这样咱们就不用在释放 建立新对象来保存内容而是能够直接将现有的集合制空再次使用。
java中list集合经过clear()方法清空,只会将list中的对象变成垃圾回收清空,可是list对象仍是存在。 可是经过list=null后,不只列表中的对象变成了垃圾,为列表分配的空间也会回收,什么都不作与赋值NULL同样,说明直到程序结束也用不上列表list了,它天然就成为垃圾了.clear()只是清除了对象的引用,使那些对象成为垃圾.