Ashhar Hasan Ashhar Hasan - 1 year ago 63
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
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);


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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download