Win a copy of Kotlin for Android App Development this week in the Kotlin 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
  • Liutauras Vilda
  • Devaka Cooray
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • salvin francis
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

Overriding hashCode() method  RSS feed

 
Ranch Hand
Posts: 72
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?
 
Master Rancher
Posts: 3887
45
  • 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: 72
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Clear and straightforward answer, thank you!
 
Marshal
Posts: 62881
203
  • 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: 72
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: 62881
203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that is what I noticed.
 
I've got no option but to sell you all for scientific experiments. Or a tiny ad:
Programmatically Create PDF Using Free Spire.PDF with Java
https://coderanch.com/wiki/703735/Programmatically-Create-PDF-Free-Spire
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!