Hashed value without hashCode definition¶
ID: java/hashing-without-hashcodeKind: problemSecurity severity: Severity: errorPrecision: very-highTags: - quality - reliability - correctnessQuery suites: - java-security-and-quality.qls
Click to see the query in the CodeQL repository
Classes that define anequals method but nohashCode method can lead to unexpected results if instances of those classes are stored in a hashing data structure. Hashing data structures expect that hash codes fulfill the contract that two objects thatequals considers equal should have the same hash code. This contract is likely to be violated by such classes.
Recommendation¶
Every class that implements a customequals method should also provide an implementation ofhashCode.
Example¶
In the following example, classPoint has no implementation ofhashCode. CallinghashCode on two distinctPoint objects with the same coordinates would probably result in different hash codes. This would violate the contract of thehashCode method, in which case objects of typePoint should not be stored in hashing data structures.
classPoint{intx;inty;Point(intx,inty){this.x=x;this.y=y;}publicbooleanequals(Objecto){if(!(oinstanceofPoint))returnfalse;Pointq=(Point)o;returnx==q.x&&y==q.y;}}
In the modification of the above example, the implementation ofhashCode for classPoint is suitable because the hash code is computed from exactly the same fields that are considered in theequals method. Therefore, the contract of thehashCode method is fulfilled.
classPoint{intx;inty;Point(intx,inty){this.x=x;this.y=y;}publicbooleanequals(Objecto){if(!(oinstanceofPoint))returnfalse;Pointq=(Point)o;returnx==q.x&&y==q.y;}// Implement hashCode so that equivalent points (with the same values of x and y) have the// same hash codepublicinthashCode(){inthash=7;hash=31*hash+x;hash=31*hash+y;returnhash;}}
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.