Ashhar Hasan Ashhar Hasan - 5 months ago 7
Java Question

Correct way to override hashCode() for persistent entity containing a boolean field?

private long configKeyMasterId;
private String configKey;
private boolean isDisplay;

public int hashCode() {
int result = (int) (configKeyMasterId ^ (configKeyMasterId >>> 32));
result = 31 * result + (configKey != null ? configKey.hashCode() : 0);
result = 31 * result + (isDisplay != null ? isDisplay.hashCode() : 0);
return result;
}


This is what I have where
isDisplay
is a boolean field. I know that the 3rd line is wrong, but how do I fix it?

Is something as naive as,

result = 31 * result + (isDisplay != false ? Boolean.hashCode(isDisplay) : 0);


okay?

I don't know how or why exactly the
hashCode()
has to be overriden but I'm reading up on it.

Answer

Checking for false is redundant. Just do

result = 31 * result + Boolean.hashCode(isDisplay);

EDIT Note that this assumes isDisplay is a primitive field. If it's a boxed field (Boolean), the version you posted (with the null check) should be correct.

Comments