The HIRO Says

If you smell what The HIRO is cooking!!!

equals() メソッドの実装(5)−Eclipseに自動生成させてみた

Eclipse(v3.2.0)のメニューに、「ソース(S)→hashCode() および equals() の生成(H)」なるものがあったので、どんなコードを生成するのか見てみました。

生成されたコード

    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (!super.equals(obj))
            return false;
        if (getClass() != obj.getClass())
            return false;
        final ComplicateObject other = (ComplicateObject) obj;
        if (booleanValue != other.booleanValue)
            return false;
        if (byteValue != other.byteValue)
            return false;
        if (charValue != other.charValue)
            return false;
        if (dateValue == null) {
            if (other.dateValue != null)
                return false;
        } else if (!dateValue.equals(other.dateValue))
            return false;
        if (Double.doubleToLongBits(doubleValue) != Double.doubleToLongBits(other.doubleValue))
            return false;
        if (Float.floatToIntBits(floatValue) != Float.floatToIntBits(other.floatValue))
            return false;
        if (intValue != other.intValue)
            return false;
        if (longValue != other.longValue)
            return false;
        if (shortValue != other.shortValue)
            return false;
        if (stringValue == null) {
            if (other.stringValue != null)
                return false;
        } else if (!stringValue.equals(other.stringValue))
            return false;
        return true;
    }

感想

なんか色々と問題ありげな…

  1. そもそも Object#equals() と違う実装をしたいので、「!super.equals(obj)」は不要では?
  2. 引数を null にすると、「if (getClass() != obj.getClass())」でぬるぽが(゚д゚)
  3. キャストの時に final 定義しているのは手堅いかも。
  4. float型は、Float.floatToIntBits() を使うんですね。(hashCode() の実装時に必要)
  5. double型は、Double.doubleToLongBits() を使うんですね。(hashCode() の実装時に必要)