Skip to main content
ICT
Lesson AB28 - Sets and Maps
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

B. TreeSet page 4 of 11

  1. 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.

  2. 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.

  3. 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

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.