override equals方法来比较java中的多个字段 [英] override equals method to compare more than one field in java

查看:112
本文介绍了override equals方法来比较java中的多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中重写equals方法以比较多个字段的最佳方法是什么?例如,我在类中有4个对象,o1,o2,o3,o4,我希望将所有这些对象与传递的对象进行比较,使用equals方法。

What is the best way to override equals method in java to compare more than one field? For example, I have 4 objects in the class, o1, o2, o3, o4 and I want compare all of them with the passed object to the equals method.

if (o1 != null && o2 != null && o3 != null && o4 != null && obj.o1 != null
    && obj.o2 != null && obj.o3 != null && obj.o4 != null
    && o1.equals(obj.o1) && o2.equals(obj.o2) && o3.equals(obj.o3) && o4.equals(obj.o4)) {
    do something
}

这段代码的问题在于它不清楚,如果我们有更多字段,就不能轻易修改。有没有更好的方法来实现这一目标?

The problem with this code is that it's not clear and can't be modified easily specially if we have more fields. Is there a better way to achieve that?

推荐答案

一种便宜的方法:

Arrays.asList(o1, o2, o3, o4).equals(Arrays.asList(obj.o1, obj.o2, obj.o3, obj.o4));

这篇关于override equals方法来比较java中的多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆