This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes CompareTo in java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "CompareTo in java" Watch "CompareTo in java" New topic

CompareTo in java

Jean Perry

Joined: Mar 12, 2013
Posts: 6
So I need compare two objects, and I hear that the best way is to use the compareTo method in the Comparable class. I understand how to use it it and the syntax of it. However...... I seem to not understand how to implement it. meaning I can't use it in my program, because the compiler can not find the compareTo method. I have gone to JavaDocs but, I don't really understand all the requirements I must meet. Can someone elaborate? preferably give a basic example?
Greg Charles

Joined: Oct 01, 2001
Posts: 2963

Your class should implement Comparable. Does it? Maybe you should post a simple example of what you're doing.
Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

Jean Perry wrote:So I need compare two objects,

In what way? Equal/not equal? Then just override and use the equals() method. If you want your class to have a "natural order," then you'd implement Comparable and define compareTo(). Note, however, that unless you're implementing a sort algorithm yourself (e.g. quicksort, mergesort, bubblesort, ...), you'll rarely if ever call compareTo() directly in your code.

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 45309
Go through this tutorial and look particularly at the section about object ordering.
Bhavesh Saraswat

Joined: Jan 20, 2013
Posts: 18

I think first of all you have to be clear and specific about the context in which you need to compare objects. I mean whether you want to sort a collection or you want to test the eqality of objects. After that it will be easy to understand which stretegy is required to compare.

By the way "Comparable" is an interface NOT a class which you implement to make your class eligible for comparision during sorting with the help of either Collections.sort() of Arrars.sort().

Collections.sort() is an utility static method to sort a colletion type and Arrays.sort() is for sorting arrays.

I agree. Here's the link:
subject: CompareTo in java
It's not a secret anymore!