In Java, add(e) puts the element e into a HashSet when the set does not already contain an equal element. It returns true if the set changed and false if e was already there.
Two elements count as the same when equals() says so and their hashCode() values match. That is why a set of String or Integer values never holds duplicates, and why your own classes must override both methods to behave the same way.
An instance method of java.util.HashSet (class since Java 1.2): a set of unique elements kept in a hash table, with no guaranteed order, one null element allowed, and no thread safety.
Syntax
One argument; the return value tells you whether it was new.
Java
Set<String> tags = new HashSet<>();
boolean first = tags.add("java"); // true: added
boolean again = tags.add("java"); // false: already there
Call
What it does
set.add("java")
Adds the element; true if it was new.
if (!seen.add(id)) { ... }
A one-line duplicate check: false means "seen before".
set.add(null)
Allowed once in a HashSet.
set.add(5)
Autoboxing turns the int into an Integer.
add() never replaces an existing element. If an equal element is already stored, the old object stays and the new one is simply dropped.
Library declarations
Java
// java.util.HashSet<E>
public boolean add(E e)
// Declared in Set<E> and Collection<E>
Parameters
Parameter
Description
e (E)
The element to add. It may be null, but only one null can be stored.
Return Value
Return Value
Description
true
The set did not contain an equal element, so e was added.
false
An equal element was already present; the set is unchanged and the original element is kept.
HashSet iteration order is not guaranteed. This is the typical output on OpenJDK 8–21; other JDKs or versions may print the entries in a different order.
How It Works
New elements return true. "java" and "spring" were not in the set yet, so both calls report true and the set grows to two elements.
A repeat returns false. The second add("java") finds an equal String already stored, changes nothing, and returns false.
Size counts distinct elements. Three add() calls were made, yet size() is 2 because "java" is stored once.
Bucket order. The tags print in the order of their buckets, which has nothing to do with the order of the calls above.
Example 2 — Count Unique Visitors with the Return Value
Use the boolean from add() to tell first visits from repeat visits.
Java
import java.util.HashSet;
import java.util.Set;
public class HashSetAddVisitors {
public static void main(String[] args) {
String[] visits = {"u7", "u3", "u7", "u9", "u3", "u7"};
Set<String> seen = new HashSet<>();
int repeats = 0;
for (String user : visits) {
if (!seen.add(user)) {
repeats++;
}
}
System.out.println("total visits: " + visits.length);
System.out.println("unique users: " + seen.size());
System.out.println("repeat visits: " + repeats);
}
}
Output
total visits: 6
unique users: 3
repeat visits: 3
How It Works
One call does two jobs.seen.add(user) both stores the id and reports whether it was new, so no separate contains() check is needed.
Negate to find repeats.!seen.add(user) is true only for ids that were stored earlier, so repeats grows for the second "u7", the second "u3", and the third "u7".
The arithmetic. Six visits minus three repeats leaves three unique users: u7, u3, and u9.
No order needed. Only counts are printed, so the result is the same on every JDK.
Example 3 — Duplicates Depend on equals() and hashCode()
The same two coupon codes are added to a set of plain objects and to a set of objects that override equals() and hashCode().
Java
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class HashSetAddObjects {
static class PlainCode {
final String text;
PlainCode(String text) { this.text = text; }
}
static class Code {
final String text;
Code(String text) { this.text = text; }
@Override
public boolean equals(Object o) {
return o instanceof Code && ((Code) o).text.equals(text);
}
@Override
public int hashCode() {
return Objects.hash(text);
}
}
public static void main(String[] args) {
Set<PlainCode> plain = new HashSet<>();
System.out.println("plain 1: " + plain.add(new PlainCode("SAVE10")));
System.out.println("plain 2: " + plain.add(new PlainCode("SAVE10")));
System.out.println("plain size: " + plain.size());
Set<Code> proper = new HashSet<>();
System.out.println("proper 1: " + proper.add(new Code("SAVE10")));
System.out.println("proper 2: " + proper.add(new Code("SAVE10")));
System.out.println("proper size: " + proper.size());
}
}