The example aims to get the size or number of elements stored in Java HashSet object.
Source Code
package com.beginner.examples;
import java.util.HashSet;
public class GetSizeOfHashSetExample {
public static void main(String[] args) {
// Create a HashSet object
HashSet hSet = new HashSet();
// Add elements
hSet.add("A");
hSet.add("B");
hSet.add("C");
hSet.add("D");
//Use the size() method in the HashSet class to get the total number of elements
int size = hSet.size();
System.out.println("Total number of elements:"+size);
}
}
Output:
Total number of elements:4
References
Imported packages in Java documentation: