In Java, add(e) inserts e into a TreeSet at its sorted position and returns true. If the set already holds an element that compares as equal, the new element is ignored and add() returns false.
Unlike a list, you never choose an index. The red-black tree compares e against existing elements using natural ordering (Comparable) or the set's Comparator, placing it in O(log n) time.
An instance method of java.util.TreeSet (Java 1.2+): a red-black tree NavigableSet backed by a TreeMap that keeps unique elements sorted in O(log n) time and is not thread-safe.
Syntax
Pass the element to insert; inspect the boolean return value to detect duplicates.
Java
NavigableSet<Integer> ids = new TreeSet<>();
boolean first = ids.add(105); // true: [105]
boolean second = ids.add(102); // true: [102, 105]
boolean dup = ids.add(105); // false: still [102, 105]
Call
What it does
set.add(e)
Inserts e in sorted order; returns true if new.
if (!set.add(x))
One-step check to catch duplicate values.
set.add(42)
Autoboxes int into Integer.
set.addAll(c)
Adds all elements of another collection.
When two objects compare as 0 under a custom Comparator, add() keeps the first inserted object and drops the later one.
Library declarations
Java
// java.util.TreeSet<E>
public boolean add(E e)
// Declared in Set<E> and Collection<E>
Parameters
Parameter
Description
e (E)
The element to add. Must be comparable with the other elements; cannot be null under natural ordering.
Return Value
Return Value
Description
true
No matching element existed, so e was inserted in sorted order.
false
An element comparing as 0 was already present; the set did not change.
Compare with Similar Methods
Other ways to put elements into a sorted set or collection:
Natural order forbids null. Calling add(null) triggers NullPointerException because natural comparison cannot rank null.
Comparable required.Badge neither implements Comparable nor has a Comparator, so adding even the first element throws ClassCastException.
Opt into nulls explicitly. Wrapping natural order in Comparator.nullsFirst places null safely ahead of "Amy" and "Zed".
Frequently Asked Questions
It returns true if the element was new and inserted into the set, or false if an equal element (according to compareTo or the Comparator) was already present.
No. Like other Set implementations, TreeSet keeps the original element and leaves the set unchanged when add() returns false.
Under natural ordering, TreeSet calls compareTo on the elements, which rejects null. Use a null-safe comparator such as Comparator.nullsFirst if you need null.
Your class does not implement Comparable and no Comparator was passed to the TreeSet constructor, so Java cannot compare two instances.
Each insertion takes O(log n) time because TreeSet stores elements in a balanced red-black tree.