Did I implement equals and hashCode correctly using Google Guava?

前端 未结 3 2206
长发绾君心
长发绾君心 2021-02-20 17:18

I am using hibernate and need to override equals and hashCode(). I chose to use google-guava\'s equals and hashCode helpers.

I wanted to know if I am missing something

3条回答
  •  庸人自扰
    2021-02-20 17:59

    You could actually use the Guava EqualsTester to test your equals and hashCode implementation:

    new EqualsTester()
         .addEqualityGroup("hello", "h" + "ello")
         .addEqualityGroup("world", "wor" + "ld")
         .addEqualityGroup(2, 1 + 1)
         .testEquals();
    

    It's in the guava testlib.

    
        com.google.guava
        guava-testlib
        test
    
    

    Minor change to your implementation:

    @Override public boolean equals(final Object obj) {
        if(obj == this) return true;
        return obj instanceof ImageEntity &&
            Objects.equal(getFilePath(), ((ImageEntity) obj).getFilePath());
    }
    

提交回复
热议问题