clear method of List collection

 

1. List.clear() underlying source code implementation

I'm used to list=null when using list combination; I'm creating this way, but I find it's good to use the clear method of list, especially when there are a lot of loops

1. The source code of the clear() method of the ArrayList class of the list interface

as follows:

/** 

     * 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;  

    }  

 

We can find from this that all objects in the list collection are released, and the collection is also empty, so we don't need to create the list collection multiple times and only need to call the clear() method.

 

 

2. The source code of the clear() method of the LinkedList class of the list interface

as follows:

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++;  

   }  


 

As we can see from the above, no matter which implementation class the clear method is, all the elements in it are released and the properties in it are emptied, so that we don't need to release and create new objects to save the content, but can directly delete the existing ones. The set of nulls is used again.

 

2. The difference between list.clear() and list = null

The list collection in java is emptied by the clear() method, which will only turn the objects in the list into garbage collection and empty, but the list object still exists. 
But after passing list=null, not only the objects in the list become garbage, but the space allocated for the list will also be recycled. Doing nothing is the same as assigning NULL, indicating that the list will not be used until the end of the program, it will naturally become garbage.clear() just clears the references to objects, making those objects garbage. 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325025407&siteId=291194637