Menu
Coddy logo textTech

Empty and Size

Part of the Logic & Flow section of Coddy's Java journey — lesson 26 of 59.

The isEmpty() method checks if a HashSet contains no elements and returns true if it is empty, or false otherwise.

The size() method returns the number of elements in the HashSet.

For example, let’s first create a HashSet:

HashSet<String> set = new HashSet<>();

To check if the set is empty:

System.out.println(set.isEmpty());
// Output: true
set.add("Coddy");
System.out.println(set.isEmpty());
// Output: false

The size() method returns the number of elements in the set:

System.out.println(set.size());
// Output: 1
challenge icon

Challenge

Easy

Create a method named <strong>checkSet</strong> that takes a HashSet of Strings as input. The method should print two lines:

  • "Empty: <true/false>" indicating whether the set is empty.
  • "Size: <number>" indicating the number of elements in the set.

Cheat sheet

The isEmpty() method checks if a HashSet contains no elements and returns true if empty, false otherwise:

HashSet<String> set = new HashSet<>();
System.out.println(set.isEmpty()); // true

set.add("Coddy");
System.out.println(set.isEmpty()); // false

The size() method returns the number of elements in the HashSet:

System.out.println(set.size()); // 1

Try it yourself

import java.util.HashSet;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;

public class Main {
    public static void checkSet(HashSet<String> set) {
        // Write your code here
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // Read JSON string representing a HashSet (e.g., ["Apple","Banana"])
        String setString = scanner.nextLine();
        
        Type setType = new TypeToken<HashSet<String>>(){}.getType();
        HashSet<String> set = new Gson().fromJson(setString, setType);
        
        checkSet(set);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow