Java


JAVA.IDEF.NOEQUALS : Missing Equals Override (Java)

要旨

equals() is inherited but extra fields have been added.

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.

プロパティ

クラス名 Missing Equals Override (Java)
日本語クラス名 Missing Equals Override (Java)
クラス分類 信頼性 (reliability)
ニーモニック JAVA.IDEF.NOEQUALS
カテゴリー
CWE CWE:1023 Incomplete Comparison with Missing Factors
CERT-Java CERT-Java:MET08-J Preserve the equality contract when overriding the equals() method
対応言語 Java で利用可能です。
有効/無効設定 このワーニングクラスのチェックはデフォルトで有効になっています。チェックを無効にするにはプロジェクト設定ファイル (configuration file)に以下の WARNING_FILTER ルールを追加してください。
WARNING_FILTER += discard class="Missing Equals Override (Java)"

// Base.java
public class Base {
  public String b;

  public Base(String b) {
      this.b = b;
  }

  public boolean equals(Object other) {
      if(other instanceof Base)
          return b.equals(((Base) other).b);
      return false; 
  }
}
// BPlus.java
public class BPlus extends Base {
    public String in;
    
    public BPlus(String b, String in) { // "Missing Equals Override (Java)" warning issued here
        super(b);
        this.in = in;
    }
}

The BPlus class extends Base class, then in addition to all the other implications of inheritance it also inherits the equals method of Base class. However, BPlus contains a in field that is not contained in Base. This means that the inherited equals does not consider in field and might be inconsistent. If in is relevant for the comparison, BPlus should overwrite the method as follows.

public class BPlus extends Base {
  public String in;
    
  public BPlus(String b, String in) {
      super(b);
      this.in = in;
  }

  public boolean equals(Object other) {
      if( super.equals(other) && other instanceof BPlus)
          return in.equals(((BPlus) other).in);
      return false; 
  }
}

解決法

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

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

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