The HashSet.size()
method in Java is used to get the number of elements in a HashSet
. This guide will cover the method’s usage, explain how it works, and provide examples to demonstrate its functionality.
Table of Contents
- Introduction
size
Method Syntax- Examples
- Getting the Size of a HashSet
- Checking Size After Adding and Removing Elements
- Conclusion
Introduction
The HashSet.size()
method is a member of the HashSet
class in Java. It allows you to determine the number of elements currently stored in the HashSet
. This method is useful for checking the size of the set at any point during its usage.
size Method Syntax
The syntax for the size
method is as follows:
public int size()
- The method does not take any parameters.
- The method returns an
int
representing the number of elements in theHashSet
.
Examples
Getting the Size of a HashSet
The size
method can be used to get the number of elements in a HashSet
.
Example
import java.util.HashSet;
public class SizeExample {
public static void main(String[] args) {
// Creating a HashSet of Strings
HashSet<String> languages = new HashSet<>();
// Adding elements to the HashSet
languages.add("Java");
languages.add("Python");
languages.add("C");
// Getting the size of the HashSet
int size = languages.size();
// Printing the size of the HashSet
System.out.println("Size of HashSet: " + size);
}
}
Output:
Size of HashSet: 3
Checking Size After Adding and Removing Elements
You can use the size
method to check the size of the HashSet
after performing operations like adding or removing elements.
Example
import java.util.HashSet;
public class SizeAfterOperationsExample {
public static void main(String[] args) {
// Creating a HashSet of Strings
HashSet<String> languages = new HashSet<>();
// Adding elements to the HashSet
languages.add("Java");
languages.add("Python");
languages.add("C");
// Printing the size of the HashSet
System.out.println("Size of HashSet after adding elements: " + languages.size());
// Removing an element from the HashSet
languages.remove("Python");
// Printing the size of the HashSet after removal
System.out.println("Size of HashSet after removing an element: " + languages.size());
// Adding more elements to the HashSet
languages.add("C++");
languages.add("JavaScript");
// Printing the size of the HashSet after adding more elements
System.out.println("Size of HashSet after adding more elements: " + languages.size());
}
}
Output:
Size of HashSet after adding elements: 3
Size of HashSet after removing an element: 2
Size of HashSet after adding more elements: 4
Conclusion
The HashSet.size()
method in Java provides a way to get the number of elements in a HashSet
. By understanding how to use this method, you can efficiently manage the size of your collections in Java applications. This method is particularly useful for scenarios where you need to know the current size of the set to make decisions or perform operations based on the number of elements.