SortedSet interface is derived from Set interface. Set interface is very unique in the whole collections hierarchy. All the derived classes of Set interface like HashSet and TreeSet does not allow duplicate elements, a unique characteristic of all collections classes. The SortedSet interface adds one more feature of returning the elements in ascending order (known as natural order). This is equivalent to SortedMap.
The elements added to a SortedSet (its subclass TreeSet) must be able to get compared with Comparator interface (using compare() method); if unable to compare, the JVM throws ClassCastException.
Following is the interface signature
Following are the abstract methods as defined in SortedSet interface
- Comparator comparator(): Returns a Comparator object associated with the SortedSet or null if the SortedSet uses natural ordering.
- Object first(): Returns the first (that is, lowest as elements are ordered in ascending order by default) present in the SortedSet.
- Object last(): Returns the last (that is, highest) present in the SortedSet.
- SortedSet subSet(int start, int end): Returns a SortedSet object that contains the elements from start and ending with end-1.
- SortedSet tailSet(Object ele): Returns a SortedSet object that contains the all the elements that are greater or equal to the element ele.
The above methods SortedSet interface are illustrated in TreeSet programs.