Java


JAVA.IDEF.EQUALS.NONOBJ : equals Parameter Should Be Object (Java)

要旨

equals() is defined against a class other than Object.

Redefinitions of the equals()/hashCode() methods from java.lang.Object must be consistent in the sense that, for instance, if two objects are equals() then hashCode() must yield the same value on both. The validity of such a property is in general undecidable, but most incorrect definitions amount to simple cases, where one of the two methods is missing. However, it is often correct to redefine only one of those methods and the analyzer is aware of many such situations.

Inconsistent definitions of equals()/hashCode() induce unexpected behaviors when objects are put inside most Collection classes of the standard Java library.

プロパティ

クラス名 equals Parameter Should Be Object (Java)
日本語クラス名 equals Parameter Should Be Object (Java)
クラス分類 信頼性 (reliability)
ニーモニック JAVA.IDEF.EQUALS.NONOBJ
カテゴリー
CWE CWE:1076 Insufficient Adherence to Expected Conventions
対応言語 Java で利用可能です。
有効/無効設定 このワーニングクラスのチェックはデフォルトで有効になっています。チェックを無効にするにはプロジェクト設定ファイル (configuration file)に以下の WARNING_FILTER ルールを追加してください。
WARNING_FILTER += discard class="equals Parameter Should Be Object (Java)"

Adding fields while redefining classes

If a class defines its equals() method and a subclass adds an instance field without redefining equals(), this checker will issue a warning since the extra field should likely be included in the test of equals(). That might however not be the case, if for instance the value of the extra field is the same when two objects are equals(). In that case, it is possible to annotate the extra field with @IrrelevantForEquals, so that this checker will not issue any more warning for that situation.

Consider the following class:

public class Foo {
  private String f;

  public Foo(String f) {
      this.f = f;
  }

  public boolean equals(Foo other) { // "equals Parameter Should Be Object (Java)" warning issued here
      return f.equals(other.f);
  }
}      

The equals method is inherited from the Object class and it should be overwritten. In particular, Object.equals() expects Object as parameter type. The the equals() method should be rewritten as follows.

  public boolean equals(Object other) {
      if(other instanceof Foo)
          return f.equals(((Foo) other).f);
      return false; 
  } 

解決法

Make equals() consistent with hashCode(). In many cases, this just amounts to provide the missing definition for one of them.

関連のある設定ファイルパラメータ

設定ファイルの以下のパラメータがこのワーニングクラスのチェックに影響します。