Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

comparable interface

 
meeta gaur
Ranch Hand
Posts: 305
Notepad Tomcat Server Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I ain't getting this compareTo() definition, in compareTo method there is another compareTo method ? how it is working ?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • 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
Notepad Tomcat Server Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much.
 
vinay chaturvedi
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic