Java HashSet add() Method
add() The method is HashSet one of the most commonly used methods in the class; its role is to add an element to the set.
Method Syntax
public
boolean
add
(
E e
)
Parameter Description
E e: the element to be added to the set
Return Value
- If the setdoes not containthe element, the addition succeeds and returns
true - If the setalready containsthe element, it will not be added and returns
false
Basic Example
Example
import
java.util.HashSet
;
public
class
HashSetExample
{
public
static
void
main
(
String
[
]
args
)
{
// Create a HashSet
HashSet
<
String
fruits
=
new
HashSet
<>
(
);
// Add elements
boolean
isAdded1
=
fruits.
add
(
"Apple"
)
;
// Returns true
boolean
isAdded2
=
fruits.
add
(
"Banana"
)
;
// Returns true
boolean
isAdded3
=
fruits.
add
(
"Apple"
)
;
// Returns false because Apple already exists
System
.
out
.
println
(
fruits
)
;
// Output: [Apple, Banana]
System
.
out
.
println
(
"First addition of Apple: "
isAdded1
)
;
System
.
out
.
println
(
"First addition of Banana: "
isAdded2
)
;
System
.
out
.
println
(
"Second addition of Apple: "
isAdded3
)
;
}
}
Underlying Principle of the add() Method
Understand add() Understanding how the method works helps us use it better HashSet.
Process of Adding an Element
- Calculate the hash value: first calculate the hash value of the element to be added
hashCode() - Determine the storage location: determine the storage location of the element in the hash table based on the hash value
- Check whether it already exists:
equals() method to compare whether elements are equal- Decide whether to add:
falseImportant Notes
HashSetDepends on the element'shashCode()andequals()Method- If you want to store custom objects, you must correctly override these two methods
- Incorrect implementation may cause abnormal collection behavior
Time Complexity of the add() Method
HashSet 's add() The time complexity of the method in the ideal case (no hash collisions) is O(1). This means that no matter how many elements are in the set, the time to add a new element is roughly the same.
However, in extreme cases (all elements hash to the same position), the time complexity degrades to O(n), because it needs to traverse the linked list or red-black tree to check whether the element already exists.
Practical Applications of the add() Method
Example 1: Deduplication
Example
import
java.util.HashSet
;
public
class
DeduplicationExample
{
public
static
void
main
(
String
[
]
args
)
{
String
[
]
names
=
{
"Alice"
,
"Bob"
,
"Alice"
,
"Charlie"
,
"Bob"
}
;
HashSet
<
String
uniqueNames
=
new
HashSet
<>
(
);
for
(
String
name
:
names
)
{
uniqueNames.
add
(
name
)
;
}
System
.
out
.
println
(
uniqueNames
)
;
// Output: [Alice, Bob, Charlie]
}
}
Example 2: Counting the Number of Unique Elements
Example
import
java.util.HashSet
;
public
class
UniqueCounter
{
public
static
void
main
(
String
[
]
args
)
{
int
[
]
numbers
=
{
1
,
2
,
3
,
2
,
4
,
1
,
5
}
;
HashSet
<
Integer
uniqueNumbers
=
new
HashSet
<>
(
);
for
(
int
num
:
numbers
)
{
uniqueNumbers.
add
(
num
)
;
}
System
.
out
.
println
(
"Number of unique elements: "
uniqueNumbers.
size
(
)
)
;
// Output: 5
}
}
Frequently Asked Questions
1. Why does the add() method return false when adding a duplicate element?
Because HashSet The design principle of does not allow duplicate elements. When trying to add an element that already exists, the set does not change and the method returns false to indicate that the add operation did not actually occur.
2. How to determine whether two elements are "the same"?
HashSet Use the following rules to determine whether two elements are the same:
- First compare
hashCode()Return Value - If the hash values are the same, then call
equals()method to compare
Only when the two elements' hashCode() are the sameand equals() Return true is it considered the same element.
3. Can you add a null value?
Yes,HashSet allows adding null values, but only once (because sets do not allow duplicates).
Example
HashSet
<
String
set
=
new
HashSet
<>
(
);
set.
add
(
null
)
;
// Returns true
set.
add
(
null
)
;
// Returns false
Summary
HashSet'sadd()The method is used to add elements to the set- If the element already exists, it will not be added and returns
false - The time complexity of this method is O(1) in the ideal case
- Correct Usage
HashSetRequires understandinghashCode()andequals()the role of the method HashSetis very suitable for scenarios that require fast lookup and deduplication
By mastering add() With the usage and principles of the method, you can make better use of HashSet to solve various programming problems.
Java HashSet