The add() method is one of the most commonly used methods in the HashSet class. Its purpose is to add an element to the collection.
Method Syntax
public boolean add(E e)
Parameter Description
E e: The element to be added to the collection
Return Value
- Returns
trueif the element was not already present in the collection - Returns
falseif the element was already present in the collection
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 add Apple: " + isAdded1);
System.out.println("First add Banana: " + isAdded2);
System.out.println("Second add Apple: " + isAdded3);
}
}
Underlying Principle of the add() Method
Understanding how the add() method works helps us use HashSet more effectively.
Process of Adding Elements
- Calculate Hash Value: First, calculate the
hashCode()of the element to be added - Determine Storage Location: Determine the storage location in the hash table based on the hash value
- Check if Already Exists:
- If the location is empty, store the element directly
- If the location is not empty, call the
equals()method to compare if 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 in different positions within the same bucket
- If the elements are the same, do not add and return
Important Notes
HashSetrelies 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 collection behavior
Time Complexity of the add() Method
The add() method of HashSet has a time complexity of O(1) in the ideal case (no hash collisions). This means the time to add a new element is roughly the same regardless of how many elements are in the collection.
However, in extreme cases (all elements hash to the same location), the time complexity degrades to O(n), because it requires traversing a linked list or red-black tree to check if 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: Count 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
}
}
FAQ
1. Why does the add() method return false when adding duplicate elements?
Because HashSet is designed not to allow duplicate elements. When trying to add an element that already exists, the collection remains unchanged, and the method returns false to indicate that the add operation did not actually occur.
2. How to determine if two elements are "the same"?
HashSet uses the following rules to determine if two elements are the same:
- First compare the return value of
hashCode() - If the hash values are the same, then call the
equals()method to compare
Only when both hashCode() are the same and equals() returns true are the elements considered the same.
3. Can null values be added?
Yes, HashSet allows adding null values, but only once (because the collection does not allow duplicates).
Example
HashSet<String> set = new HashSet<>(); set.add(null); // returns true set.add(null); // returns false
YouTip