• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problems with compareTo method  RSS feed

 
Amit Chohan
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all
hope all is well
would someone be kind enough to help me with the following query. The following compare to method throws the following exception -

Error - missing return statement
public int compareTo(Object obj){
^
Thanks
 
Fred Close
Ranch Hand
Posts: 42
Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it's because the compiler expect that there could be an other else
so this would be ok
public int compareTo(Object obj){
Appointment app = (Appointment)obj;
if (slot > app.slot)
return slot - app.slot;
else if (slot < app.slot)
return slot - app.slot;
else // i.e. (slot == app.slot)
return slot - this.slot;

}
 
John Dale
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The complier doesn't consider the inter-relationsihp between the three conditions in your if statements to determine that one of the returns will always be executed. So as far as the complier is concerned, it could evalutate all three of the if conditions, not get a match, and thus fall out the bottom. You could "fix" it by adding a return 0 at the bottom.
Is there any difference between your code and

Also, don't forget that when you provide compareTo(), you usually need to override equals() and hashCode().
 
Amit Chohan
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much :roll:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!