SortedSet Interface

If we wish to maintain a set in ascending order, we need to use the TreeSet implementation of the SortedSet interface.

CollectExample

import java.util.*;

public class CollectExample
{

public static void main(String[] args)
{
Collection c = new TreeSet();;
c.add(''Smith");
c.add("Jones");
c.add("Smith");

c.add(''Brown");
c.add("Able");
Iterator i = c.iterator();
while (i.hasNext() ) {
System.out.print(i.next() + " ");
}
}
}



No other changes need to be made. The program output will now be

> java CollectExample
Able Brown Jones Smith


The order of this SortedSet is a consequence of the String class implementing the Comparable interface. There is only one method in Comparable, namely, compareTo. The compareTo method determines the ordering; in the case of the String implementation of compareTo, this is in lexicographic order. The Java Integer class (the object wrapper for int) and Date class, for example, also implement the Comparable interface. The Integer class compareTo method sorts the set in signed numerical order. The Date class compareTo method sorts the set in chronological order.

The SortedSet interface inherits all the methods of the Set interface. In addition, SortedSet provides a number of methods, such as first and last, which make sense only for a set that is sorted. There is only one implementation of SortedSet, namely, TreeSet. To use the noninherited methods, we need to replace the statement

Collection c = new TreeSet();

with

SortedSet c = new TreeSet();

The statements

System.out.println("first: " + c.first());
System.out.println("last: " + c.last());


will produce the output

first: Able
last: Smith

No comments:

Post a Comment