Best implementation for hashCode method for a collection

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

    For a simple class it is often easiest to implement hashCode() based on the class fields which are checked by the equals() implementation.

    public class Zam {
        private String foo;
        private String bar;
        private String somethingElse;
    
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
    
            if (obj == null) {
                return false;
            }
    
            if (getClass() != obj.getClass()) {
                return false;
            }
    
            Zam otherObj = (Zam)obj;
    
            if ((getFoo() == null && otherObj.getFoo() == null) || (getFoo() != null && getFoo().equals(otherObj.getFoo()))) {
                if ((getBar() == null && otherObj. getBar() == null) || (getBar() != null && getBar().equals(otherObj. getBar()))) {
                    return true;
                }
            }
    
            return false;
        }
    
        public int hashCode() {
            return (getFoo() + getBar()).hashCode();
        }
    
        public String getFoo() {
            return foo;
        }
    
        public String getBar() {
            return bar;
        }
    }
    

    The most important thing is to keep hashCode() and equals() consistent: if equals() returns true for two objects, then hashCode() should return the same value. If equals() returns false, then hashCode() should return different values.

提交回复
热议问题