Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashcode and equals query

 
Mili Dua
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone. This is my first post in the JavaRanch SCJP forums and the look and the feel of this place is uber best .
I have a query regarding the HASHCODE AND EQUALS CONCEPT and I figure this is the best place to ask -:

[[As per the contract of hash code() --

1. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

2. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.]]


IS THERE ANY POSSIBILITY THAT or i should say that whether it can happen that the two objects are unequal but calling the hashcode() method on each of them must produce the same integer result ??
 
Gaurangkumar Khalasi
Ranch Hand
Posts: 187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mili Dua wrote:IS THERE ANY POSSIBILITY THAT or i should say that whether it can happen that the two objects are unequal but calling the hashcode() method on each of them must produce the same integer result ??

Yes it is possible...
For example, you can override hashCode() method in your class as following than it will return same integer for all its instances either equal or unequal.

Note: It is not an appropriate way to override but it is a legal override example of hashCode().
 
Phani Kiran Rudravarapu
Greenhorn
Posts: 3
Android Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mili Dua wrote: IS THERE ANY POSSIBILITY THAT or i should say that whether it can happen that the two objects are unequal but calling the hashcode() method on each of them must produce the same integer result ??


Is there a possibility that two objects are unequal but calling hashCode produces the same integer result? Yes, if the hashCode method is not properly overridden.

Are there any scenarios where it should be like this? No. This kind of hashCode implementation is an inefficient one. Legal, but inefficient.

To avoid scenarios like these, the same instance variables used in overridden equals method are used in the overridden hashCode method. And static and transient variables are not supposed to be used.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic