CodeQL documentation

Inconsistent equals and hashCode

ID: java/inconsistent-equals-and-hashcode
Kind: problem
Security severity: 
Severity: error
Precision: very-high
Tags:
   - reliability
   - correctness
   - external/cwe/cwe-581
Query suites:
   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

A class that overrides only one of equals and hashCode is likely to violate the contract of the hashCode method. The contract requires that hashCode gives the same integer result for any two equal objects. Not enforcing this property may cause unexpected results when storing and retrieving objects of such a class in a hashing data structure.

Recommendation

Usually, both methods should be overridden to ensure that they are consistent.

Example

In the following example, the class InconsistentEqualsHashCode overrides hashCode but not equals.

public class InconsistentEqualsHashCode {
	private int i = 0;
	public InconsistentEqualsHashCode(int i) {
		this.i = i;
	}

	public int hashCode() {
		return i;
	}
}

In the following example, the class InconsistentEqualsHashCodeFix overrides both hashCode and equals.

public class InconsistentEqualsHashCodeFix {
	private int i = 0;
	public InconsistentEqualsHashCodeFix(int i) {
		this.i = i;
	}

	@Override
	public int hashCode() {
		return i;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		InconsistentEqualsHashCodeFix that = (InconsistentEqualsHashCodeFix) obj;
		return this.i == that.i;
	}
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy