concept TreeSet in category java

appears as: TreeSet, The TreeSet, TreeSet
Get Programming with Java

This is an excerpt from Manning's book Get Programming with Java.

In this lesson, we are concentrating on the Set interface. Lesson 21 introduces the Java Collection along with an overview of all the interfaces and classes that extend from the Collection Interface.  Figure 22.1 shows the Java Collection Framework with only the Set interfaces and classes.  As you can see, there are two classes that extend directly from the Set interface: HashSet and LinkedHashSet.  The TreeSet extends the SortedSet interface which extends the Set interface. The TreeSet is different since it requires the elements to be sorted, but it still follows the rule that all elements in a Set must be unique, no duplicates.

Code listing 22.4 uses a TreeSet to hold a list of animals at the zoo:

Code Listing 22.4 sample code to create a set of values in sorted order using a TreeSet
1.      package lesson22;
 2.     
 3.      import java.util.Arrays;
 4.      import java.util.Set;
 5.      import java.util.TreeSet;
 6.     
 7.      public class Lesson22_Listing4 {
 8.          public static void main(String[] args){
 9.              Set animals = new TreeSet();   //#A
 10.             animals.add("Lion");           //#B
 11.             animals.add("Bear");           //#B
 12.             animals.add("Tiger");          //#B
 13.             System.out.println(Arrays.toString(animals.toArray()));
 14.         }
 15.     }

Listing 22.4 creates a Set reference variable, animals, that is instantiated as a TreeSet. Three animals are added to the set.  Since the TreeSet stores the elements in sorted order, the output is: [Bear, Lion, Tiger].  The TreeSet collection can be created using the Set interface, the SortedSet interface and the class name TreeSet.  Listing 22.5 is similar to the code listing from 22.4, but this time there are two differences. On line 9 I have changed the set type from Set to SortedSet and added an additional statement on line 13.