Java LinkedList clear() Method

Java LinkedList Java LinkedList


clear()The method is a commonly used method in JavaLinkedListprovided by the class, used to remove all elements from the linked list. After calling this method, the linked list becomes an empty list.

Method Syntax

public void clear()

Method Description

clear()The main functions of the method are:

  1. RemoveLinkedListall elements in
  2. Reset the size of the linked list to 0
  3. Does not affect the capacity of the linked list, becauseLinkedListthere is no capacity limit

Usage Examples

Basic Usage

Example

import java.util.LinkedList;

public class ClearExample {
    public static void main(String[] args) {
        // Create a LinkedList
        LinkedList<String> fruits = new LinkedList<>();
       
        // Add elements
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
       
        System.out.println("LinkedList before clearing: " + fruits);
        System.out.println("Size before clearing: " + fruits.size());
       
        // Use the clear() method to clear the linked list
        fruits.clear();
       
        System.out.println("LinkedList after clearing: " + fruits);
        System.out.println("Size after clearing: " + fruits.size());
    }
}

Output:

清空前的链表: [Apple, Banana, Cherry]
清空前的大小: 3
清空后的链表: []
清空后的大小: 0

Implementation Principle

In Java'sLinkedListimplementation,clear()the method works through the following steps:

  1. Traverse all nodes in the linked list
  2. Set the predecessor and successor references of each node to null
  3. Set the head node (first) and tail node (last) of the linked list to null
  4. Set the size of the linked list to 0

This implementation approach helps the garbage collector to reclaim node objects that are no longer used.


Method Characteristics

  1. Time complexity: O(n) - needs to traverse all nodes
  2. Space complexity: O(1) - no extra storage space needed
  3. Thread safety: Not thread-safe, requires external synchronization in a multi-threaded environment
  4. Return value: None (void)

Notes

  1. After callingclear()the method, all elements in the linked list will be removed and cannot be recovered.
  2. If the linked list is shared by multiple references, all references will see the effect of the linked list being cleared.
  3. After clearing the linked list, new elements can be added.
  4. andnew LinkedList<>()Unlike creating a new instance,clear()the method reuses the existing object.

Comparison with Other Methods

Method Function Time Complexity Whether it modifies the original linked list
clear() Clear all elements O(n) Yes
removeAll() Remove all elements in the specified collection O(n*m) Yes
new LinkedList<>() Create a new empty linked list O(1) no

Practical Application Scenarios

clear()The method is particularly useful in the following scenarios:

  1. Reusing linked list objects: When you need to reuse the same linked list object
  2. Memory management: When you need to release the memory occupied by the linked list
  3. Reset state: When you need to reset the state of the linked list during algorithms or data processing

Example

// Practical application example: processing batch data
LinkedList<Data> dataBuffer = new LinkedList<>();

// Phase 1: Collect data
collectData(dataBuffer);

// Process data
processData(dataBuffer);

// Clear the buffer to prepare for the next batch of data
dataBuffer.clear();

// Phase 2: Collect new data
collectData(dataBuffer);

By using theclear()method appropriately, you can improve the efficiency and readability of your code.

Java LinkedList Java LinkedList

Other Extensions