+ 1
What should we write in hashCode() method when overriding equal()
Say 'class A' has three members 'int a, float b and String name'.
2 ответов
+ 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.
}
0
pls elaborate "equal object must have same hashcode,But object having same hash code may not be equal."