Javaの:カスタム実装のequals()メソッド
通常のカスタム日付タイプは、例えば、経験の浅い人は、これまでの直接比較は、達成するために以下のことを書くことを感じることがあり
public class MyDate implements Comparable<MyDate> {
private final int year;
private final int month;
private final int day;
public MyDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
@Override
public int compareTo(MyDate o) {
throw new NotImplementedException();
}
public boolean equals(Date that) {
if (this.day != that.day) {
return false;
}
if (this.month != that.month) {
return false;
}
if (this.year != that.year) {
return false;
}
return true;
}
}
しかし、我々は強力なのequals()メソッドを達成したい、上記のコードは、次の符号は十分ではありません
//定义为final类型:允许子类直接使用父类equals()方法是不安全的
public final class MyDate implements Comparable<MyDate> {
private final int year;
private final int month;
private final int day;
public MyDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
@Override
public int compareTo(MyDate o) {
throw new NotImplementedException();
}
@Override
//规定参数必须是Object类型
public boolean equals(Object obj) {
//检查是否相同引用
if (obj == this) {
return true;
}
//检查null
if (obj == null) {
return false;
}
//getClass()判断的是准确的运行时类型,instanceof的类型可以是父类或接口
if (obj.getClass() != this.getClass()) {
return false;
}
//这里类型转换一定是安全的
MyDate that = (MyDate) obj;
//确认关键字段都相等
if (this.day != that.day) {
return false;
}
if (this.month != that.month) {
return false;
}
if (this.year != that.year) {
return false;
}
return true;
}
}
カスタムは、ルーチンの方法に等しいです
- 同じ参照するかどうかを確認し、もしそうであれば、trueを返します
- ヌル値をチェックし、もしそうならば、falseを返します。
- 同じタイプが異なる場合は、falseを返すかどうかをチェックし、同じ型変換の場合
- 各キーワード群と比較
フィールドが使用、プリミティブ型の場合4.1==
フィールドは、のオブジェクトのequals()メソッドを使用して、型のオブジェクトである場合4.2
フィールドが配列、配列比較の各要素である場合4.3。使用を検討してArrays.equals(a,b)
かArrays.deepEquals(a,b)
、ではなく、a.equals(b)
提案
- フィールドの値が他のフィールドの値に完全に依存している場合は、比較することはできません
- フィールド内の最も可能性の高い最初の比較の違い
- オブジェクトが実装した場合
compareTo()
の方法は、直接使用するために使用することができます。例えばx.compareTo(y) == 0