The override equals method to compare multiple fields in Java

What is the best way to rewrite the equals method in Java to compare multiple fields? For example, I have four objects in my class, O1, O2, O3, O4. I want to compare all these objects with the passed objects and use 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 is not clear. If we have more fields, we can't modify them easily Is there a better way to achieve this goal?

Solution

One cheap way is:

Arrays.asList(o1,o4).equals(Arrays.asList(obj.o1,obj.o2,obj.o3,obj.o4));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>