• 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
  • Bear Bibeault
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Frits Walraven
Bartenders:
  • Carey Brown
  • salvin francis
  • Claude Moore

Overriding hashCode() method  RSS feed

 
Ranch Hand
Posts: 77
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: 4017
47
  • 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: 77
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Clear and straightforward answer, thank you!
 
Marshal
Posts: 64086
215
  • 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: 77
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: 64086
215
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that is what I noticed.
 
You've gotta fight it! Don't give in! Read this tiny ad:
Create Edit Print & Convert PDF Using Free API with Java
https://coderanch.com/wiki/703735/Create-Convert-PDF-Free-Spire
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!