This week's book giveaway is in the Web Services forum.
We're giving away four copies of Microservices in Action and have Morgan Bruce & Paulo A. Pereira on-line!
See this thread for details.
Win a copy of Microservices in Action this week in the Web Services forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Overriding hashCode() method  RSS feed

 
Ranch Hand
Posts: 66
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Question about overriding the hashCode() method. The OCP study guide book states (page 19 just above the real world scenario) that the following situation is not legal:


The book states: it is not legal because it uses more variables than the equals() method which looked like:


So from what I understand it is not legal to use the age variable in the hashCode() method because it is not used in the equals method.

My question is: why is this 'not legal'? I tested it and it does compile but what do they mean with it is not legal?
 
Rancher
Posts: 3767
40
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Part of the contract of hashcode is that two objects that are equal (ie the equals method return true) have the same hash code.
I your example, if you had two objects with the same idNumber, but different ages, then equals would return true, but they would have different hash codes.
 
Bart Boersma
Ranch Hand
Posts: 66
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Clear and straightforward answer, thank you!
 
Marshal
Posts: 61805
193
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . and did they tell you what the error in that equals() method is?
 
Bart Boersma
Ranch Hand
Posts: 66
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess you are aiming at the method parameter of the equals method that takes the object type Lion rather than the object type Object which would turn it from an overloaded equals method to an overridden equals method which is more common

Am I right?
 
Campbell Ritchie
Marshal
Posts: 61805
193
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that is what I noticed.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!