CodeQL documentation

Inconsistent equals and hashCode

ID: java/inconsistent-equals-and-hashcode
Kind: problem
Security severity: 
Severity: error
Precision: very-high
Tags:
   - quality
   - 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
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy