Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java HashSet clear() Method

Java HashSet clear() Method

Java HashSet Java HashSet


clear() The method is in Java's HashSet is a commonly used method provided by the class, used to remove all elements from the collection. After calling this method, the collection becomes an empty set.

Method Signature:

Method Syntax

public

void

clear

(

)

Method Functionality

clear() The main functions of the method are:

  1. Removes the HashSet all elements in the
  2. reset the collection size to 0
  3. does not change the collection's capacity, only clears the content

Usage examples

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 collection

        fruits.

clear

(

)

;

       

       

System

.

out

.

println

(

"Set after clearing: "

fruits

)

;

       

System

.

out

.

println

(

"Size after clearing: "

fruits.

size

(

)

)

;

   

}

}

Output result:

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

Technical Details

Underlying Implementation Principle

  1. HashSet Internally uses HashMap to store elements
  2. clear() method actually calls the underlying HashMap 's clear() Method
  3. This method traverses all hash buckets and sets each bucket to null

Time Complexity

Memory Handling

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

Notes

  1. Thread Safety:

  2. HashSet Although the Date class is still usable in many cases, it has some obvious limitations:
  3. Using in a multi-threaded environment clear() method requires additional synchronization measures
  4. - `HashSet` is not thread-safe - Using the `clear()` method in a multi-threaded environment requires additional synchronization measures
    1. Difference from removeAll():

    2. clear() directly clears the entire collection
    3. removeAll() requires passing another collection as a parameter, only removes the intersection
    4. - `clear()` directly clears the entire collection - `removeAll()` requires passing another collection as a parameter, only removing the intersection
      1. Empty Collection Check:

      2. After clearing, you can use isEmpty() method to check whether the collection is empty

        Example

        if (fruits.isEmpty()) {
          System.out.println("Collection cleared");
        }
      3. - After clearing, you can use the `isEmpty()` method to check whether the collection is empty

        Example

        if (fruits.isEmpty()) {
          System.out.println("Collection cleared");
        }

        Practical Application Scenarios

        1. Reset Collection State:

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

          2. When you are sure the elements in the collection are no longer needed, clearing the collection can help with garbage collection
          3. - When you are sure the elements in the collection are no longer needed, clearing the collection can help with garbage collection
            1. Data Cleanup:

            2. When processing temporary data collections, use clear() to ensure no old data is left behind
            3. - When processing temporary data collections, use `clear()` to ensure no old data is left behind

              Frequently Asked Questions

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

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

              Q2: Is the collection null after clear()?

              No.clear() Afterward, the collection object still exists, just without any elements. This is a different concept 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, create a new one

              largeSet

              =

              new

              HashSet

              <>

              (

              )

              ;

              // If the collection is not large or needs to be reused

              largeSet.

              clear

              (

              )

              ;


              Summary

              HashSet 's clear() method is a simple but practical tool that can quickly clear collection content. Understanding its working principle and applicable scenarios can help developers manage collection data better. Remember that it only clears elements without changing the capacity, which needs attention in memory-sensitive applications.

              Java HashSet Java HashSet