override equals method to compare more than one field in java

后端 未结 6 551
予麋鹿
予麋鹿 2021-01-14 11:53

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 t

6条回答
  •  执念已碎
    2021-01-14 12:41

    Use a utility method to help you

    private static boolean nullSafeEquals(Object o1, Object o2) {
        if(o1 == null && o2 == null) return true; // both null, both equal
        if(o1 == null || o2 == null) return false; // if one is null, not equal - we know both won't be null
        return o1.equals(o2);
    }
    
    public boolean equals(Object o) {
        if(o instanceof ThisClass) {
            ThisClass tc = (ThisClass)o;
            return nullSafeEquals(o1, tc.o1)
                && nullSafeEquals(o2, tc.o2)
                && nullSafeEquals(o3, tc.o3)
                && nullSafeEquals(o4, tc.o4);
        }
        return false;
    }
    

提交回复
热议问题