Name

TreeSet<E>

Synopsis

This class implements SortedSet, provides support for all optional methods, and guarantees that the elements of the set can be enumerated in ascending order. In order to be sorted, the elements of the set must all be mutually Comparable objects, or they must all be compatible with a Comparator object that is specified when the TreeSet is created. TreeSet is implemented on top of a TreeMap, so its add( ), remove( ), and contains( ) methods all operate in relatively efficient logarithmic time. If you do not need the sorting capability of TreeSet, however, use HashSet instead, as it is significantly more efficient. See Set, SortedSet, and Collection for details on the methods of TreeSet.

In order for a TreeSet to operate correctly, the Comparable or Comparator comparison method must be consistent with the equals( ) method. That is, the equals( ) method must compare two objects as equal if and only if the comparison method also indicates those two objects are equal.

The methods of TreeSet are not synchronized. If you are working in a multithreaded environment, you must explicitly synchronize code that modifies the contents of the set, or obtain a synchronized wrapper with Collections.synchronizedSet( ).

java.util.TreeSet<E>

Figure 16-64. java.util.TreeSet<E>

public class TreeSet<E> extends AbstractSet<E> implements SortedSet<E>, Cloneable, 
       Serializable {
// Public Constructors public ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.