Java HashSet clear() Method

Java HashSet Java HashSet


clear()The method is, in Java,HashSeta common method provided by the class, used to remove all elements from the set. After calling this method, the set becomes an empty set.

Method Signature:

Method Syntax

public void clear()

Method Functionality

clear()The main functions of the method are:

  1. RemoveHashSetall elements in the set
  2. Reset the size of the set to 0
  3. Do not change the capacity of the set; only clear the contents

Usage Example

Basic Usage Example

Example

import java.util.HashSet;

public class HashSetClearExample {
    public static void main(String[] args) {
        // Create a HashSet and add elements
        HashSet<String> fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
       
        System.out.println("Set before clearing: " + fruits);
        System.out.println("Size before clearing: " + fruits.size());
       
        // Use the clear() method to clear the set
        fruits.clear();
       
        System.out.println("Set after clearing: " + fruits);
        System.out.println("Size after clearing: " + fruits.size());
    }
}

Output:

清空前的集合: [Apple, Orange, Banana]
清空前的大小: 3
清空后的集合: []
清空后的大小: 0

Technical Details

Underlying Implementation Principle

  1. HashSetInternally usesHashMapto store elements
  2. clear()The method actually calls the underlyingHashMapofclear()method
  3. This method traverses all hash buckets and sets each bucket to null

Time Complexity

  • clear()The time complexity of the method is O(n), where n is the number of elements in the set
  • Because it needs to traverse all hash buckets to release references

Memory Handling

  1. After clearing the set, the JVM's garbage collector can reclaim the memory occupied by these elements
  2. ButHashSetThe capacity of the HashSet itself (the size of the hash table) does not change

Notes

  1. Thread safety:

    • HashSetNot thread-safe
    • In a multi-threaded environment, using theclear()method requires additional synchronization measures
  2. Difference from removeAll():

    • clear()Directly clears the entire set
    • removeAll()Requires passing another collection as a parameter; only removes the intersection part
  3. Empty set check:

    • After clearing, you can use theisEmpty()method to check whether the set is empty

      Example

      if (fruits.isEmpty()) {
        System.out.println(The set has been cleared);
      }

Practical Application Scenarios

  1. Reset collection state:

    • When you need to reuse the same collection object, you can clear it first and then fill it with new data
  2. Memory Management:

    • When you are sure you no longer need the elements in the collection, clearing the collection can help garbage collection
  3. Data Cleanup:

    • When processing temporary data collections, usingclear()ensures that no old data is left behind

FAQ

Q1: Does the clear() method change the capacity of the HashSet?

No.clear()The method only removes all elements, but keeps the capacity of the hash table unchanged. If you need to reduce the capacity, you need to create a new one.HashSet。

Q2: Is the set null after clear()?

No.clear()After clear(), the collection object still exists, but it does not contain any elements. This is different from setting the reference to null.

Q3: How to efficiently clear and reuse a HashSet?

Example

// If the collection is large and no longer needed, you can create a new one
largeSet = new HashSet<>();

// If the collection is not large or needs to be reused
largeSet.clear();

Summary

HashSetofclear()The method is a simple but practical tool that can quickly clear the contents of a collection. Understanding its working principle and applicable scenarios can help developers better manage collection data. Remember that it only clears elements and does not change the capacity; this should be noted in memory-sensitive applications.

Java HashSet Java HashSet

Other Extensions