Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

util.TreeSet: practical reference

util.TreeSet: practical reference: TreeSet<E> is a TreeMap-backed NavigableSet sorted naturally or by a Comparator, with add, remove, and contains guaranteed O(log n).

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

java.util.TreeSet

TreeSet is a TreeMap-backed NavigableSet sorted naturally or by a Comparator, with add, remove, and contains guaranteed O(log n).

Use it for unique elements in sort order plus lower, floor, ceiling, higher queries and range views.

Ordering must be consistent with equals to honor the Set contract; it is not synchronized, and mutating comparison state breaks lookup.

null works only when the comparator permits it; addFirst and addLast always throw UnsupportedOperationException, while first and last throw NoSuchElementException when empty.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        var set = new java.util.TreeSet<Integer>(java.util.List.of(3, 1, 2));
        System.out.println(set);
    }
}

Result

[1, 2, 3]

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources