File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes comparable interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "comparable interface" Watch "comparable interface" New topic

comparable interface

meeta gaur
Ranch Hand

Joined: Dec 05, 2012
Posts: 305

I ain't getting this compareTo() definition, in compareTo method there is another compareTo method ? how it is working ?

My one regret in life is that I am not someone else.
- Woody Allen
Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

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

Joined: Dec 05, 2012
Posts: 305

Thank you very much.
vinay chaturvedi

Joined: Jan 16, 2012
Posts: 14
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.
I agree. Here's the link:
subject: comparable interface
It's not a secret anymore!