equals() メソッドの実装(4)−データ型による実装の違い
equals() メソッドの実装にあたって、一部のデータ型については特別な処理が必要です。
特別な処理
- float型の場合、Float.compare() を呼び出す必要があります。
- double型の場合、Double.compare() を呼び出す必要があります。
- オブジェクトの参照の場合、その equals() メソッドを呼び出す必要があります。
実装例
import java.util.Date; public class ComplicateObject { // fields private boolean booleanValue; private byte byteValue; private char charValue; private short shortValue; private int intValue; private long longValue; private float floatValue; private double doubleValue; private String stringValue; private Date dateValue; @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof ComplicateObject)) { return false; } ComplicateObject target = (ComplicateObject) o; return (this.booleanValue == target.booleanValue && this.byteValue == target.byteValue && this.charValue == target.charValue && this.shortValue == target.shortValue && this.intValue == target.intValue && this.longValue == target.longValue && Float.compare(this.floatValue, target.floatValue) == 0 && Double.compare(this.doubleValue, target.doubleValue) == 0 && (this.stringValue == null ? target.stringValue == null : this.stringValue.equals(target.stringValue)) && (this.dateValue == null ? target.dateValue == null : this.dateValue.equals(target.dateValue))); } // getter/setter/constructor は省略 }