|
An implementation of a SortedSet
is the TreeSet class,
which uses a tree as its implementation:
Object
AbstractCollection (implements Collection)
AbstractSet (implements Set)
TreeSet (implements SortedSet)
package examples;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetExample
{
public static void main(String[] args)
{
TreeSet set = new TreeSet();
set.add("Mary");
set.add("Frank");
set.add("Joe");
set.add("Sylvia");
set.add("Vanessa");
set.add("Frank"); // Duplicate
for (Iterator iter = set.iterator(); iter.hasNext(); )
{
String name = (String) iter.next(); // Note required cast
System.out.println(name);
}
}
}
|
Note the minimal changes to the program from the earlier HashSet
example. This is a consequence of the consistent use of
interfaces, and having different implementations that use the same interface.
Here's the output of the example:
Frank
Joe
Mary
Sylvia
Vanessa
which shows that we still have no duplicates, but that the elements are now
returned in the
proper order (in this case, alphabetically).
|