• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

CompareTo in java

 
Jean Perry
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2985
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your class should implement Comparable. Does it? Maybe you should post a simple example of what you're doing.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Go through this tutorial and look particularly at the section about object ordering.
 
Bhavesh Saraswat
Greenhorn
Posts: 18
Java Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic