This week's book giveaway is in the Programmer Certification forum.
We're giving away four copies of OCP Oracle Certified Professional Java SE 21 Developer Study Guide: Exam 1Z0-830 and have Jeanne Boyarsky & Scott Selikoff on-line!
See this thread for details.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Problems with compareTo method

 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 42
Mac
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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;

}
 
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you very much :roll:
 
Hey cool! They got a blimp! But I have a tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic