This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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 Android Security Essentials Live Lessons this week in the Android 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: 172
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: 3606
    
  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).
 
wood burning stoves
 
subject: Sorting in Collection framework
 
Similar Threads
Doubt pertaining to compare() in TreeSet
Ordered and Sorted
TreeSet - insertion of Objects
code
comparator and comparable interfaces