Best implementation for hashCode method for a collection

后端 未结 20 3069
难免孤独
难免孤独 2020-11-22 01:39

How do we decide on the best implementation of hashCode() method for a collection (assuming that equals method has been overridden correctly) ?

20条回答
  •  醉话见心
    2020-11-22 02:18

    If you're happy with the Effective Java implementation recommended by dmeister, you can use a library call instead of rolling your own:

    @Override
    public int hashCode() {
        return Objects.hashCode(this.firstName, this.lastName);
    }
    

    This requires either Guava (com.google.common.base.Objects.hashCode) or the standard library in Java 7 (java.util.Objects.hash) but works the same way.

提交回复
热议问题