UPDATED:
Set s = new HashSet();
s.add(1);
s.add(5);
s.add(4);
s.add(9);
s.add(7);
s.add(8);
s.add(\"
HashSet does not guaranteed that its contents will be sorted in any way. There is a special interface for sets that do provide such a guarantee: it's called SortedSet:
A
Setthat further provides a total ordering on its elements. The elements are ordered using their natural ordering, or by aComparatortypically provided at sorted set creation time. The set's iterator will traverse the set in ascending element order. Several additional operations are provided to take advantage of the ordering. (This interface is the set analogue ofSortedMap.)
In Java 6, there are two classes that implement this interface: ConcurrentSkipListSet and TreeSet.