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: trueset.add("Coddy");
System.out.println(set.isEmpty());
// Output: falseThe size() method returns the number of elements in the set:
System.out.println(set.size());
// Output: 1Challenge
EasyCreate 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()); // falseThe size() method returns the number of elements in the HashSet:
System.out.println(set.size()); // 1Try 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);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays4HashSet Part 1
What is a HashSet?Adding an ElementRemoving an ElementChecking if an Element ExistsEmpty and SizeClear and CloneRecap - HashSet2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap