GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • CodeQL documentation
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL language guides
  • QL language reference
  • CodeQL standard-libraries
  • CodeQL query help
  • CodeQL repository
  • QL publications
  • CodeQL query help for C and C++
  • CodeQL query help for C#
  • CodeQL query help for GitHub Actions
  • CodeQL query help for Go
  • CodeQL query help for Java and Kotlin

This view

  • Original page
  • New address

GeezerVison is showing codeql.github.com — Inconsistent equals and hashCode — CodeQL query help 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-code-quality.qls
   - 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¶

  • J. Bloch, Effective Java (second edition), Item 9. Addison-Wesley, 2008.

  • Java API Specification: Object.equals, Object.hashCode.

  • IBM developerWorks: Java theory and practice: Hashing it out.

  • Help - Eclipse Platform: Java Compiler Errors/Warnings Preferences.

  • Common Weakness Enumeration: CWE-581.

  • © GitHub, Inc.
  • Terms
  • Privacy
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.