Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Overloaded equals

ID: java/wrong-equals-signatureKind: problemSecurity severity: Severity: errorPrecision: mediumTags:   - quality   - reliability   - correctnessQuery suites:   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

Classes that define anequals method whose parameter type is notObjectoverload theObject.equals method instead ofoverriding it. This may not be intended.

Recommendation

Tooverride theObject.equals method, the parameter of theequals method must have typeObject.

Example

In the following example, the definition of classBadPoint does not override theObject.equals method. This means thatp.equals(q) resolves to the default definition ofObject.equals and returnsfalse. ClassGoodPoint correctly overridesObject.equals, so thatr.equals(s) returnstrue.

classBadPoint{intx;inty;BadPoint(intx,inty){this.x=x;this.y=y;}// overloaded equals method -- should be avoidedpublicbooleanequals(BadPointq){returnx==q.x&&y==q.y;}}BadPointp=newBadPoint(1,2);Objectq=newBadPoint(1,2);booleanbadEquals=p.equals(q);// evaluates to falseclassGoodPoint{intx;inty;GoodPoint(intx,inty){this.x=x;this.y=y;}// correctly overrides Object.equals(Object)publicbooleanequals(Objectobj){if(obj!=null&&getClass()==obj.getClass()){GoodPointq=(GoodPoint)obj;returnx==q.x&&y==q.y;}returnfalse;}}GoodPointr=newGoodPoint(1,2);Objects=newGoodPoint(1,2);booleangoodEquals=r.equals(s);// evaluates to true

References


[8]ページ先頭

©2009-2025 Movatter.jp