Java TreeSet add() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
TreeSet

Definition

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]
CallWhat 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

ParameterDescription
e (E)The element to add. Must be comparable with the other elements; cannot be null under natural ordering.

Return Value

Return ValueDescription
trueNo matching element existed, so e was inserted in sorted order.
falseAn 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:

MethodHow it differs
addAll(c)Inserts every element from another collection in one call.
contains(o)Checks membership without inserting anything.
remove(o)Deletes a matching element instead of adding one.
ArrayList.add(e)Keeps insertion order and allows both duplicates and null.

Java Examples

Example 1 — Insert Unordered Ticket Numbers and Catch Duplicates

Add raffle ticket IDs out of order, print each return value, and confirm duplicates are ignored.

Java
import java.util.TreeSet;

public class TreeSetAddTickets {
    public static void main(String[] args) {
        TreeSet<Integer> tickets = new TreeSet<>();
        System.out.println("add 304: " + tickets.add(304));
        System.out.println("add 108: " + tickets.add(108));
        System.out.println("add 205: " + tickets.add(205));
        System.out.println("add 205 again: " + tickets.add(205));

        System.out.println("sorted tickets: " + tickets);
        System.out.println("count: " + tickets.size());
    }
}

How It Works

  1. Automatic sorting on insert. Passing 304, 108, then 205 returns true for each and arranges them as 108, 205, 304.
  2. Duplicate ticket blocked. The second add(205) finds 205 already in the tree and returns false.
  3. Unique count stays at three. Three unique tickets remain in ascending order inside tickets.

Example 2 — Natural String Order vs a Case-Insensitive Comparator

See how natural ordering puts uppercase words first, while a case-insensitive comparator keeps only the first spelling.

Java
import java.util.TreeSet;

public class TreeSetAddStrings {
    public static void main(String[] args) {
        TreeSet<String> natural = new TreeSet<>();
        natural.add("zeta");
        natural.add("Beta");
        natural.add("alpha");
        System.out.println("natural: " + natural);

        TreeSet<String> tags = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        System.out.println("add Java: " + tags.add("Java"));
        System.out.println("add java: " + tags.add("java"));
        tags.add("Cloud");
        System.out.println("case-insensitive: " + tags);
    }
}

How It Works

  1. Code-unit comparison. Natural String ordering places capital letters before lowercase ones, so "Beta" precedes "alpha".
  2. Comparator equality wins. Under String.CASE_INSENSITIVE_ORDER, "java" compares as 0 against "Java" even though equals() is false.
  3. Original spelling kept. Because "Java" arrived first, add("java") returns false and leaves "Java" in the set.

Example 3 — NullPointerException, ClassCastException, and nullsFirst()

Adding null or an uncomparable class throws under natural order, while Comparator.nullsFirst accepts null.

Java
import java.util.Comparator;
import java.util.TreeSet;

public class TreeSetAddErrors {
    static class Badge {
        final String code;
        Badge(String code) { this.code = code; }
    }

    public static void main(String[] args) {
        TreeSet<String> names = new TreeSet<>();
        try {
            names.add(null);
        } catch (NullPointerException e) {
            System.out.println("natural null: " + e.getClass().getSimpleName());
        }

        TreeSet<Badge> badges = new TreeSet<>();
        try {
            badges.add(new Badge("VIP"));
        } catch (ClassCastException e) {
            System.out.println("no Comparable: " + e.getClass().getSimpleName());
        }

        TreeSet<String> optional = new TreeSet<>(Comparator.nullsFirst(Comparator.naturalOrder()));
        optional.add("Zed");
        optional.add(null);
        optional.add("Amy");
        System.out.println("nullsFirst set: " + optional);
    }
}

How It Works

  1. Natural order forbids null. Calling add(null) triggers NullPointerException because natural comparison cannot rank null.
  2. Comparable required. Badge neither implements Comparable nor has a Comparator, so adding even the first element throws ClassCastException.
  3. 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.

Next: addAll()

Add every element of another collection in sorted order.

addAll() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful