This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan 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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "CompareTo in java" Watch "CompareTo in java" New topic
Author

CompareTo in java

Jean Perry
Greenhorn

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
Sheriff

Joined: Oct 01, 2001
Posts: 2840
    
  11

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

Joined: Jan 03, 2004
Posts: 6109
    
    6

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
Sheriff

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

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.


OCPJP SE6
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: CompareTo in java
 
Similar Threads
Object Comparable
compareTo method
Unsorted array list
a question about a String method...
Help Please