HashSet isEmpty() Method in Java

Published by user on

The isEmpty() method of HashSet checks if the HashSet is empty or not. If the HashSet is empty then it returns true otherwise returns false.
More formally, it returns true if the size of the HashSet is equal to zero. If the size is greater than zero then the isEmpty() method returns false.

Syntax

public boolean isEmpty()

Parameters

It does not accept any parameter.

Return Value

It returns true if the HashSet is empty otherwise returns false.

Program 1

import java.util.HashSet;

// This program shows
// how to use isEmpty() method
// to check if the HashSet is empty or not
public class HashSetIsEmptyExample {
	public static void main(String[] args) {
		// Create an instance of HashSet
		HashSet<Integer> set = new HashSet<>();
		// Add elements to it
		set.add(10);
		set.add(20);
		set.add(30);
		set.add(40);
		set.add(50);

		// Display hashSet elements
		System.out.println("Set Elements : " + set);
		// HashSet has values here
		// So, isEmpty() returns false
		System.out.println("Is Set Empty? : " + set.isEmpty());
		// Clear the hashSet
		set.clear();
		// HashSet is empty here
		// So, call to isEmpty() returns true
		System.out.println("Is Set Empty? : " + set.isEmpty());
	}
}

Output

Set Elements : [50, 20, 40, 10, 30]
Is Set Empty? : false
Is Set Empty? : true

Explanation

  1. Create an instance of HashSet
  2. Add elements 10, 20, 30, 40, 50 to it
  3. Check if the HashSet is empty using the isEmpty() method. As the HashSet has values in it. So, the call to isEmpty() method returns false.
  4. Clear the HashSet. At this point, there are no elements in the HashSet.
  5. Call to the isEmpty() method returns true now.

Program 2

import java.util.HashSet;

// This program shows
// how to use isEmpty() method
// to check if the HashSet of String elements
// is empty or not
public class HashSetIsEmptyExample {
	public static void main(String[] args) {
		// Create an instance of HashSet
		HashSet<String> set = new HashSet<>();
		// Add elements to it
		set.add("Adam");
		set.add("Chris");
		set.add("Charles");
		set.add("Robert");

		// Display hashSet elements
		System.out.println("Set Elements : " + set);
		// HashSet has values here
		// So, isEmpty() returns false
		System.out.println("Is Set Empty? : " + set.isEmpty());
		// Clear the hashSet
		set.clear();
		// HashSet is empty here
		// So, call to isEmpty() returns true
		System.out.println("Is Set Empty? : " + set.isEmpty());
	}
}

Output

Set Elements : [Adam, Charles, Robert, Chris]
Is Set Empty? : false
Is Set Empty? : true
Categories: Java

0 Comments

Leave a Reply

Avatar placeholder

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