Java HashSet size() Method
size()The method is in JavaHashSeta built-in method of the class, used to return the number of elements in the current collection. Its method signature is as follows:
Method Syntax
Return Value
This method returns aninttype value, representingHashSetthe number of elements currently stored in the instance.
Important Notes
- The return value is always a non-negative integer
- When the set is empty, returns 0
- The return value reflects the size of the set at the time of the call; subsequent add/remove operations will change this value
Usage Examples
Basic Usage
Example
public class HashSetSizeExample {
public static void main(String[] args) {
// Create a new HashSet
HashSet<String> fruits = new HashSet<>();
// Add elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// Use the size() method to get the set size
int size = fruits.size();
System.out.println("Number of elements in HashSet: " + size); // Output: 3
}
}
Empty Set Case
Example
System.out.println("Size of empty HashSet: " + numbers.size()); // Output: 0
Dynamic Changes
Example
System.out.println("Initial size: " + letters.size()); // Output: 0
letters.add('A');
letters.add('B');
System.out.println("Size after adding: " + letters.size()); // Output: 2
letters.remove('A');
System.out.println("Size after removal: " + letters.size()); // Output: 1
Technical Details
Time Complexity
size()The time complexity of the method is O(1), becauseHashSetit internally maintains a counter to track the number of elements, rather than recalculating on each call.
Difference from Capacity
size()It returns the actual number of stored elements- Capacity refers to the size of the underlying hash table and can be set via the constructor
- Capacity is usually greater than or equal to size
Example
System.out.println(set.size()); // Output: 0 (because there are no elements yet)
Practical Application Scenarios
1. Check if the set is empty
Although you can useisEmpty()method, butsize() == 0is also a common practice.
Example
System.out.println("Shopping cart is empty");
}
2. Limit set size
Example
// ...
if (activeUsers.size() >= MAX_ACTIVE_USERS) {
System.out.println("Maximum number of active users reached");
}
3. Performance Monitoring
Example
log.info("Current cache entry count: " + cache.size());
Notes
Concurrent Environment:
HashSetis not thread-safe; in a multi-threaded environment, usingsize()may get inaccurate results. Consider usingConcurrentHashMapor a synchronized wrapper.Cooperation with Other Collection Methods:
Example
// Check size first to avoid unnecessary operations
if (set1.size() == set2.size() && set1.containsAll(set2)) {
System.out.println("The two sets are equal");
}
Memory Considerations: Large
HashSetwill take up more memory; regularly checkingsize()can help identify memory issues.
Summary
HashSetofsize()The method is a simple but very useful tool that provides a quick snapshot of the current state of the collection. Understanding and correctly using this method can help you write more efficient and reliable Java code.
Java HashSet