How do I implement a good hashcode if there are two boolean fields? Usually people just add the integer values to their hashcode values. But if I simply add 1 or 0 to my hashcode, I do not think it is good. Because if I have two objects of class A:
obj1.b = true, obj1.c = false.
obj2.b = false, obj2.c = true.
Everyting else is the same. Then the hashcode for these two unequal objects are the same. I know this situation is okay. But imagine if there are 100 boolean fields, then there would be too much collision right? I do not want so many different objects to fall in the same bucket.
What I did below is to assign different numbers to different truth values for each field so objects hashcodes can be very different.
public class A {
private final String a;
private final boolean b;
private final boolean c;
...
@Override public int hashCode(){
int i,j;
if(b) {
i = 10;
}
else {
i = 0;
}
if(c) {
j = 88;
}
else {
j = 3;
}
int result = 0;
result = 31*result + i + j;
result = 31*result + (a != null ? a.hashCode() : 0);
return result;
}
}