Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to customize the implementation of the equals () method by Java

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

这篇文章主要介绍了Java如何自定义实现equals()方法,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

以常见的自定义Date类型为例,没有经验的朋友可能会觉得直接比较年月日即可,从而写出以下的实现

public class MyDate implements Comparable { 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 { 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()方法"这篇文章对大家有帮助,同时也希望大家多多支持,关注行业资讯频道,更多相关知识等着你来学习!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report