Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java HashSet size() Method

Java HashSet size() Method

Java HashSet Java HashSet


size() The method is in Java's HashSet is a 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

public

int

size

(

)

Return Value

The method returns a int a value of type, representing HashSet the number of elements currently stored in the instance.

Important Notes


Usage examples

Basic Usage

Example

import

java.util.HashSet

;

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 collection size

       

int

size

=

fruits.

size

(

)

;

       

System

.

out

.

println

(

"Number of elements in HashSet: "

size

)

;

// Output: 3

   

}

}

Empty Collection Case

Example

HashSet

<
Integer
numbers
=
new
HashSet
<>
(
)

;

System

.

out

.

println

(

"Size of empty HashSet: "

numbers.

size

(

)

)

;

// Output: 0

Dynamic Changes

Example

HashSet

<
Character
letters
=
new
HashSet
<>
(
)

;

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 removing: "

letters.

size

(

)

)

;

// Output: 1


Technical Details

Time Complexity

size() The time complexity of the method is O(1) because HashSet internally maintains a counter to track the number of elements, rather than recalculating each time it is called.

Difference from Capacity

Example

HashSet

<
String
set
=
new
HashSet
<>
(
100
)

;

// Initial capacity 100

System

.

out

.

println

(

set.

size

(

)

)

;

// Output: 0 (because there are no elements yet)


Practical Application Scenarios

1. Check Whether the Collection Is Empty

Although you can use isEmpty() method, size() == 0 is also a common way.

Example

if

(

cartItems.

size

(

)

==

0

)

{

   

System

.

out

.

println

(

"Shopping cart is empty"

)

;

}

2. Limit Collection Size

Example

HashSet

<
User
activeUsers
=
new
HashSet
<>
(
)

;

// ...

if

(

activeUsers.

size

(

)

=

MAX_ACTIVE_USERS

)

{

   

System

.

out

.

println

(

"Maximum number of active users reached"

)

;

}

3. Performance Monitoring

Example

// Record collection sizes at different time points to monitor memory usage

log.

info

(

"Current cache entries: "

cache.

size

(

)

)

;


Notes

  1. Concurrent Environment:HashSet is not thread-safe; using it in a multi-threaded environment size() may yield inaccurate results. Consider using ConcurrentHashMap or a synchronized wrapper.

  2. Cooperation with Other Collection Methods:

Example

// Checking size first can avoid unnecessary operations
if (set1.size() == set2.size() && set1.containsAll(set2)) {
    System.out.println("Two collections are equal");
}
3.

Memory Considerations: Large HashSet will occupy more memory; regularly checking size() can help identify memory problems.


Summary

HashSet 's size() 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 Java HashSet