• 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

comparable interface

 
Ranch Hand
Posts: 305
Tomcat Server Notepad Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I ain't getting this compareTo() definition, in compareTo method there is another compareTo method ? how it is working ?
 
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The second compareTo is called on the title member variable. So that code means "DVDs should be ordered alphabetically by their title". So the thing you want to order by is a String. How to do that? Well, the String class implements Comparable, so you just have to delegate to the compareTo() method there.

By the way, you should use the generic version of Comparable. That way you avoid having to cast, and you get better type safety.
 
meeta gaur
Ranch Hand
Posts: 305
Tomcat Server Notepad Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you very much.
 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As your class is implementing Comparable interface it has to implement the compareTo() method.

The second compareTo() method is called on String variable. As you know String class also implements Comparable interface, hence it contains compareTo() method.

So the second compareTo() method that is called is of String class.

The compareTo method of String class compares the current title with the title value provided and returns an integer value (zero, negative or positive).

zero : both the values are equal.
negative : first value is less than second value
positive : first value is greater than second value.

*Note : compareTo method of Comparable is always based on natural sorting order.
reply
    Bookmark Topic Watch Topic
  • New Topic