NOTE

TreeSet

What TreeSet is, usage, constructor, fields, other methods, and summary.

JavaCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What It Is

An unordered, non-duplicating collection implemented using TreeMap.

2. Usage

public class TreeSetTest
{
    public static void main(String[] args)
    {
        TreeSet<Integer> set = new TreeSet<>();
        set.add(1);
        set.add(2);
        set.remove(2);
        System.out.println(set.contains(1));
        System.out.println(set.contains(2));
        System.out.println(set.contains(3));
    }
}

3. Source Analysis

3.1. Constructor

public TreeSet() {
    // Implemented using TreeMap underneath
    this(new TreeMap<E,Object>());
}

3.2. Fields

public class TreeSet<E> extends AbstractSet<E>
    implements NavigableSet<E>, Cloneable, java.io.Serializable
{

    // Map interface accessed according to key order
    private transient NavigableMap<E,Object> m;

    // Placeholder used as the map value
    private static final Object PRESENT = new Object();
}

3.3. Other Methods

They call TreeMap methods, with O(log N) efficiency.

4. Summary

It is implemented using TreeMap underneath, with a newly created Object used as the value placeholder.

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub