AbstractSet clear() method in Java with Example

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

Syntax:

public void clear()

Parameters: This function has no parameters.



Returns: The method does not return any value. It removes all the elements in the set and makes it empty.

Below examples illustrates the AbstractSet.clear() method:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to demonstrate the working of
// clear() method in AbstractSet
  
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
        // creating an AbstractSet
        AbstractSet<Integer> arr
            = new TreeSet<Integer>();
  
        // using add() to initialize values
        // [1, 2, 3, 4]
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(4);
  
        // set initially
        System.out.println("The set initially: "
                           + arr);
  
        // clear function used
        arr.clear();
  
        // set after clearing all elements
        System.out.println("The set after "
                           + "using clear() method: "
                           + arr);
    }
}

chevron_right


Output:

The set initially: [1, 2, 3, 4]
The set after using clear() method: []

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to demonstrate the working of
// clear() method in AbstractSet
  
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
        // creating an AbstractSet
        AbstractSet<String> arr
            = new TreeSet<String>();
  
        // using add() to initialize values
        // [Geeks, For, ForGeeks, GeeksForGeeks]
        arr.add("Geeks");
        arr.add("For");
        arr.add("ForGeeks");
        arr.add("GeeksForGeeks");
  
        // set initially
        System.out.println("The set initially: "
                           + arr);
  
        // clear function used
        arr.clear();
  
        // set after clearing all elements
        System.out.println("The set after "
                           + "using clear() method: "
                           + arr);
    }
}

chevron_right


Output:

The set initially: [For, ForGeeks, Geeks, GeeksForGeeks]
The set after using clear() method: []


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.