SortedSet interface Java

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

public interface SortedSet extends Set

Following are the abstract methods as defined in SortedSet interface
  1. Comparator comparator(): Returns a Comparator object associated with the SortedSet or null if the SortedSet uses natural ordering.
  2. Object first(): Returns the first (that is, lowest as elements are ordered in ascending order by default) present in the SortedSet.
  3. Object last(): Returns the last (that is, highest) present in the SortedSet.
  4. SortedSet subSet(int start, int end): Returns a SortedSet object that contains the elements from start and ending with end-1.
  5. 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.

3 thoughts on “SortedSet interface Java”

  1. Hi Sir, have a mistake at “The elements added to a SortedSet (its subclass TreeSet) must be able to get compared with Comparator interface (using compareTo() method)”
    – I think using compare() method, not compareTo(). Thanks sir.

Leave a Comment

Your email address will not be published.