• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting in Collection framework

 
Tarun Oohri
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Everyone
I have a doubt in sorting part of the collections.
~ If we talk about List, They are ordered but not sorted . So in order to sort them we use sort() of Collections class, where therefore invoke the compareTo() of the class implementing Comparable interface.
~ If we talk about TreeSet, they are ordered and sorted . So if we add String objects in it, It sort them in alphabetical order .
Question : TreeSet is able to sort the String objects because it itself implements Comparable interface & Hence implemented compareTo() ?
 
Martin Vajsar
Sheriff
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tarun Oohri wrote:Question : TreeSet is able to sort the String objects because it itself implements Comparable interface & Hence implemented compareTo() ?

Basically true.

A TreeSet can also be created with a Comparator that will be used to determine the order of its elements. This allows to insert elements into the set that do not implement Comparable, assuming that the comparator of the set is able to handle them, as well as using a comparator to define ordering different from the one imposed by Comparable implementation of the elements (such as having a TreeSet of Strings sorted in inverse order - using Collections.reverseOrder() for example).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic