HashSet clear() Method in Java

Published by user on

The clear() method of HashSet removes all the elements from the HashSet. The HashSet becomes empty after the call to the clear() method.

Syntax

void clear()

Parameters

It does not take any parameter and does not return anything.

Return Value

It does not return anything.

Program 1

import java.util.HashSet;

public class HashSetClearExample {

        public static void main(String[] args) {

                HashSet fruits = new HashSet();
                fruits.add("Apple");
                fruits.add("Banana");
                fruits.add("Grapes");
                fruits.add("Oranges");

                System.out.println("Set elements before clear: " + fruits);
                fruits.clear();
                System.out.println("Set elements after clear: " + fruits);
        }
}

Output

Set elements before clear: [Apple, Grapes, Oranges, Banana]
Set elements after clear: []

Program 2

import java.util.HashSet;

public class HashSetClearExample {

        public static void main(String[] args) {

                HashSet set = new HashSet();
                set.add(10);
                set.add(20);
                set.add(30);
                set.add(40);
                set.add(50);

                System.out.println("Set elements before clear: " + set);
                set.clear();
                System.out.println("Set elements after clear: " + set);
        }
}

Output

Set elements before clear: [50, 20, 40, 10, 30]
Set elements after clear: []
Categories: Java

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *