Java Set clear() isEmpty() Methods Tutorial

In this section, we will learn what the Set clear() and isEmpty() methods are and how to use them in Java.

What is Java Set clear() Method?

The Java Set clear() method is used to clear the entire elements of a Set object.

Java Set clear() Method Syntax:

void clear()

clear() Method Parameters:

The method does not take an argument.

clear() Method Return Value:

The return value of this method is void.

clear() Method Exceptions:

The method does not throw an exception.

Example: using Set clear() method

import java.util.Set;
import java.util.HashSet; 
public class Main {

    public static void main(String[] args){
      Set<Integer> set = new HashSet<>();
      set.add(1);
      set.add(2);
      set.add(3);
      set.add(4);
      set.add(5);
      set.add(6);
      set.add(7);

      System.out.println("The size of the set before calling the clear() method: "+set.size());
      set.clear();
      System.out.println("The size of the set after calling the clear() method: "+set.size());
    }
}

Output:

The size of the set before calling the clear() method: 7

The size of the set after calling the clear() method: 0

What is Java Set isEmpty() Method?

The Java Set isEmpty() method is used to check whether a Set object is empty.

Java Set isEmpty() Method Syntax:

boolean isEmpty()

isEmpty() Method Parameters:

The method does not take an argument.

isEmpty() Method Return Value:

The return value of this method is of type Boolean.

If there was an element in the target Set object, the return value of this method becomes true. Otherwise, the value false will return instead.

isEmpty() Method Exceptions:

The method does not throw an exception.

Example: using Set isEmpty() method

import java.util.Set;
import java.util.HashSet; 
public class Main {

    public static void main(String[] args){
      Set<Integer> set = new HashSet<>();
      set.add(1);
      set.add(2);
      set.add(3);
      set.add(4);
      set.add(5);
      set.add(6);
      set.add(7);

      System.out.println("Is this set empty?: "+set.isEmpty());
      set.clear();
      System.out.println("Is the set object empty after calling the clear() method?: "+set.isEmpty());
    }
}

Output:

Is this set empty?: false

Is the set object empty after calling the clear() method?: true
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies