这篇文章将为大家详细讲解有关怎么在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;
}
}
自定义equals方法的套路
检查是否是同一个引用,如果是,返回true
检查null值,如果是,返回false
检查类型是否相同,如果不同,返回false;如果相同,进行类型转换
对每个关键字段进行比较:
4.1 如果字段是基本类型,使用==
4.2 如果字段是对象类型,使用对象的equals()方法
4.3 如果字段是个数组,比较数组的每个元素。可以考虑使用Arrays.equals(a,b)或者Arrays.deepEquals(a,b),但不是a.equals
(b)
建议
如果一个字段的值完全依赖其他字段的值,可以不用比较
优先比较最可能出现差异的字段
如果对象实现了compareTo()方法,可以直接拿来使用。例如x.compareTo(y) == 0
关于怎么在Java中自定义一个equals()方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。