Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hash code and equals

 
Terrence White
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a question from Dan Chisholm's Exam:

Question 8
If two instances of a class type are not equal according to the equals method, then the same integer value must not be returned by the hashCode method of the two objects.
a. false
b. true

The listed answer is false.
Why is this not true?
[ October 07, 2002: Message edited by: Thomas Paul ]
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although it would be preferable if unequal objects produce unequal hashcodes there are not always enough hashcode values to allow for one unique hashcode for each unique object value. The Hashcode method returns a value of type int. The set of unique values for the set of Long objects greatly exceeds the number of values of type int. For that reason, many objects of type Long that are not equal must share a single hashcode value.
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this month's JavaRanch newsletter has a great article on the equals and hashcode controversy.
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And here is the link:
Equals and hashCode by Manish Hatwalne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic