1. Introduction
The size() method in Java’s HashSet class is used to get the number of elements in the set. It is a straightforward and useful method when you need to determine how many unique elements are stored in a HashSet.
2. Program Steps
1. Instantiate a HashSet and add some elements to it.
2. Use the size() method to determine the number of elements in the HashSet.
3. Print the size of the HashSet to the console.
3. Code Program
import java.util.HashSet;
public class HashSetSize {
public static void main(String[] args) {
// Step 1: Instantiate a HashSet and add some elements to it
HashSet<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Step 2: Use the size() method to determine the number of elements in the HashSet
int size = fruits.size();
// Step 3: Print the size of the HashSet to the console
System.out.println("The size of the HashSet is: " + size);
}
}
Output:
The size of the HashSet is: 3
4. Step By Step Explanation
Step 1: A HashSet named fruits is instantiated and populated with three string elements – "Apple", "Banana", and "Cherry".
Step 2: The size() method is invoked on the fruits HashSet, and the returned size is stored in the integer variable size.
Step 3: The size of the HashSet is printed to the console, which is 3, reflecting the number of unique elements added to the HashSet.