Java HashSet add() Method
add()The method isHashSetone of the most commonly used methods in the class, and its function is to add an element to the set.
Method Syntax
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
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 time adding Apple: " + isAdded1);
System.out.println("First time adding Banana: " + isAdded2);
System.out.println("Second time adding Apple: " + isAdded3);
}
}
Underlying Principle of the add() Method
Understandingadd()the working principle of the method helps us better useHashSet。
Process of Adding an Element
- Calculate the hash value: first calculate the element to be added's
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:
- If the position is empty, store the element directly
- If the position is not empty, call
equals()method to compare whether the elements are the same
- Decide whether to add:
- If the elements are the same, do not add, and return
false - If the elements are different (hash collision), they may be stored at different positions in the same bucket
- If the elements are the same, do not add, and return
Important Notes
HashSetDepends on the element'shashCode()andequals()methods- If you want to store custom objects, you must correctly override these two methods
- Incorrect implementation may cause abnormal set behavior
Time Complexity of the add() Method
HashSetofadd()The time complexity of the method is **O(1)** in the ideal case (no hash collision). 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 an extreme case (all elements hash to the same position), the time complexity degrades to **O(n)**, because it is necessary 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
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 Unique Elements
Example
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?
BecauseHashSetthe design principle (of HashSet) does not allow duplicate elements. When trying to add an already existing element, the set does not change, and the method returnsfalseto indicate that the add operation did not actually occur.
2. How to determine whether two elements are "the same"?
HashSetUse 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 equaland equals()returnstrueonly then are they considered the same element.
3. Can a null value be added?
Yes,HashSetit is allowed to addnullvalue, but it can only be added once (because the set does not allow duplicates).
Example
set.add(null); // returns true
set.add(null); // returns false
Summary
HashSetofadd()The method is used to add an element 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
- Proper use
HashSetrequires understandinghashCode()andequals()the role of the method HashSetIt is very suitable for scenarios that require fast lookup and deduplication
By masteringadd()the usage and principles of the method, you can more effectively useHashSetto solve various programming problems.
Java HashSet