override equals method to compare more than one field in java

后端 未结 6 552
予麋鹿
予麋鹿 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:49

    Use Guava:

    @Override
    public boolean equals(final Object obj){
        if (!(obj instanceof Foo)) {
            return false;
        }
        final Foo other = (Foo) obj;
        return Objects.equal(o1, other.o1)
            && Objects.equal(o2, other.o2)
            && Objects.equal(o3, other.o3)
            && Objects.equal(o4, other.o4);
    }
    

    You get hashCode() for cheap, too:

    @Override
    public int hashCode() {
        return Objects.hashCode(o1, o2, o3, o4);
    }
    

提交回复
热议问题