Java Hashset Clear
# Java HashSet clear() Method
[ Java HashSet](#)
* * *
The `clear()` method is a commonly used method provided by the `HashSet` class in Java. It removes all elements from the set. After calling this method, the set becomes an empty set.
**Method Signature**:
### Method Syntax
public void clear()
### Method Function
The main functions of the `clear()` method are:
1. Remove all elements from the `HashSet`
2. Reset the size of the set to 0
3. Do not change the capacity of the set; only clear its 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 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 empty the set
fruits.clear();
System.out.println("Set after clearing: "+ fruits);
System.out.println("Size after clearing: "+ fruits.size())
YouTip