-
The java.util.TreeSet class in the Java standard class library is an implementation of the Set interface using trees. This class uses a balanced binary search tree to keep elements in sorted order. The TreeSet class implements the Set interface, so Figure 28.1 describes TreeSet's methods as well.
-
In general, any Comparable objects may be placed into a TreeSet. This guarantees that the set will be in ascending order, as determined by the object’s compareTo method. Items in a TreeSet should also be mutually comparable, meaning that for any pair of elements e1 and e2 in the set, e1.compareTo(e2) will not throw a ClassCastException. The items in a TreeSet should all be of the same type.
-
Because of the balanced binary tree implementation, the TreeSet class provides an O(log n) run time for the operations add, remove, and contains.
import java.util.TreeSet;
import java.util.Set;
Set <String> myTree = new TreeSet <String>();
myTree.add("Nancy");
myTree.add("David");
myTree.add("David");
System.out.println(myTree.size());
for(String temp : myTree){
System.out.println(temp);
}
The output for this code fragment is
The size of the set is 2
David
Nancy