• 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

Doubt in Comparable interface

 
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Source: own study



I am not getting what the return s.compareTo(s); statement does. Is it comparing the same object against itself?
But the output of this program seems to be correct, which is:
[1, 22, 3, 4, 5]

I guess the compareTo defined in the code is not used at all. Because, the TreeSet contains String objects, and String class already implements Comparable. Is it so?

So, can I say that for TreeSet containing some third-party objects, the third-party class has to properly define the Comparable for sorting the elements? Else, the items are not sorted. Also, ClassCastException is thrown. Please correct me if I am wrong.
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Rekha,

You are right, when you put objects of test class in the TreeSet then only
the compareTo() method will be used for sorting. Here you are simply putting
objects of String into TreeSet.


Yeah, your class (what you are calling third party class) has to implement the
Comparable interface so that objects of that class could be sorted which are
on the collection.
 
Rekha Srinath
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Chandra..I got it...
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic