java.util.HashSet.clear() Method

Advertisements


Description

The clear() method is used to remove all of the elements from this set. The set will be empty after this call returns.

Declaration

Following is the declaration for java.util.HashSet.clear() method.

public void clear()

Parameters

  • NA

Return Value

NA

Exception

  • NA

Example

The following example shows the usage of java.util.HashSet.clear()

package com.tutorialspoint;

import java.util.*;

public class HashSetDemo {
   public static void main(String args[]) {
      // create hash set
      HashSet <String> newset = new HashSet <String>();      
      
      // populate hash set
      newset.add("Learning"); 
      newset.add("Easy");
      newset.add("Simply");  
            
      // checking elements in hash set
      System.out.println("Hash set values: "+ newset);
      
      // clear set values
      newset.clear();
      
      System.out.println("Hash set values after clear: "+ newset);      
   }    
}

Let us compile and run the above program, this will produce the following result.

Hash set values: [Learning, Simply, Easy]
Hash set values after clear: []



Advertisements
Advertisements