*
The moose likes Beginning Java and the fly likes How to declare compareTo() method  and invoke it from the main method? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to declare compareTo() method  and invoke it from the main method?" Watch "How to declare compareTo() method  and invoke it from the main method?" New topic
Author

How to declare compareTo() method and invoke it from the main method?

Mahi Rahman
Greenhorn

Joined: Feb 16, 2007
Posts: 21
Hi there!
I am trying to find out what would be correct syntex for declaring a compareTo() method and invoking it from the main program. I went through books but I didn't find anything related to compare two integers (but I found for String comparison). I also found suggestion for using interface but I'm not sure how to implement that. Can anyone please help me?

Mahi.


Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
First off, if you are going to write a compareTo() method in your class, then you may as well declare to the world that instances of your class can now be used wherever a Comparable<State> is expected. You do that by declaring that your class implements Comparable<State>



Now, as far as implementing a useful compareTo() method for your class, primitives (int, double, etc.) have no methods. You can not do something like this:


However the (<, >, <=, >=, ==) operators are defined for ints so you can do this.


so in your compareTo() method, when comparing primitives you should do something similar.

[ February 18, 2007: Message edited by: Garrett Rowe ]

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Mahi Rahman
Greenhorn

Joined: Feb 16, 2007
Posts: 21
Hei Garrett!
Thanks a lot for your reply. I now understand what was the problem. Cheers!
Mahi.
 
wood burning stoves
 
subject: How to declare compareTo() method and invoke it from the main method?
 
Similar Threads
Question On Comparator
Question 58 Quiz B in master exam of K&B
ID:8 SCJP Question of the day !!!
Soting objects in collection