• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Sorting in Collection framework

 
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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() ?
 
Sheriff
Posts: 3837
66
Netbeans IDE Oracle Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).
 
reply
    Bookmark Topic Watch Topic
  • New Topic