Best implementation for hashCode method for a collection

后端 未结 20 3068
难免孤独
难免孤独 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:37

    @about8 : there is a pretty serious bug there.

    Zam obj1 = new Zam("foo", "bar", "baz");
    Zam obj2 = new Zam("fo", "obar", "baz");
    

    same hashcode

    you probably want something like

    public int hashCode() {
        return (getFoo().hashCode() + getBar().hashCode()).toString().hashCode();
    

    (can you get hashCode directly from int in Java these days? I think it does some autocasting.. if that's the case, skip the toString, it's ugly.)

提交回复
热议问题