The clear() method of java.util.LinkedHashSet class is used to remove all of the elements from this set. The set will be empty after this call returns.
Syntax:
public void clear()
Return Value: This method does not return anything.
Below are the examples to illustrate the clear() method.
Example 1:
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
LinkedHashSet<Integer>
linkset = new LinkedHashSet<Integer>();
linkset.add( 10 );
linkset.add( 20 );
linkset.add( 30 );
System.out.println( "LinkedHashSet: "
+ linkset);
linkset.clear();
System.out.println( "LinkedHashSet after "
+ "use of clear() method: "
+ linkset);
}
catch (NullPointerException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
LinkedHashSet: [10, 20, 30]
LinkedHashSet after use of clear() method: []
Example 2:
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
LinkedHashSet<String>
linkset = new LinkedHashSet<String>();
linkset.add( "A" );
linkset.add( "B" );
linkset.add( "C" );
System.out.println( "LinkedHashSet: "
+ linkset);
linkset.clear();
System.out.println( "LinkedHashSet after "
+ "use of clear() method: "
+ linkset);
}
catch (NullPointerException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
LinkedHashSet: [A, B, C]
LinkedHashSet after use of clear() method: []