aspose file tools*
The moose likes Java in General and the fly likes Sorting in Collection framework Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Sorting in Collection framework" Watch "Sorting in Collection framework" New topic
Author

Sorting in Collection framework

Tarun Oohri
Ranch Hand

Joined: Feb 20, 2013
Posts: 180
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

Joined: Aug 22, 2010
Posts: 3611
    
  60

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).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sorting in Collection framework