What should we write in hashCode() method when overriding equal() | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What should we write in hashCode() method when overriding equal()

Say 'class A' has three members 'int a, float b and String name'.

25th Jun 2016, 6:18 AM
Jigar Thacker
Jigar Thacker - avatar
2 Answers
+ 4
First of all this is not nesecery to modify hashcode in every condition. Default equal method gives true if the object is same. If you modify the equal method such that you compere object of different class or type & it return true then you have to modify the hashcode method such that it return same integer for both the object. Remember equal object must have same hashcode, but object having same hash code may not be equal. for example consider objects a, b & c. now if a & b are equal according to custom equal method than you have to override hashcode method to return same hashcode in case of a & b. now if hash code of c & a are same than they can be equal. in the end, if you don't understand anything than you can simply return any integer constant, although it NOT GOOD CODING PRACTICE like.. //works in all cases. public hashcode (){ return 1; //could be any integer but constant. }
25th Jun 2016, 2:26 PM
Neel Patel
Neel Patel - avatar
0
pls elaborate "equal object must have same hashcode,But object having same hash code may not be equal."
22nd Nov 2016, 4:26 PM
rmlawal
rmlawal - avatar