Best implementation for hashCode method for a collection

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

    Here is another JDK 1.7+ approach demonstration with superclass logics accounted. I see it as pretty convinient with Object class hashCode() accounted, pure JDK dependency and no extra manual work. Please note Objects.hash() is null tolerant.

    I have not include any equals() implementation but in reality you will of course need it.

    import java.util.Objects;
    
    public class Demo {
    
        public static class A {
    
            private final String param1;
    
            public A(final String param1) {
                this.param1 = param1;
            }
    
            @Override
            public int hashCode() {
                return Objects.hash(
                    super.hashCode(),
                    this.param1);
            }
    
        }
    
        public static class B extends A {
    
            private final String param2;
            private final String param3;
    
            public B(
                final String param1,
                final String param2,
                final String param3) {
    
                super(param1);
                this.param2 = param2;
                this.param3 = param3;
            }
    
            @Override
            public final int hashCode() {
                return Objects.hash(
                    super.hashCode(),
                    this.param2,
                    this.param3);
            }
        }
    
        public static void main(String [] args) {
    
            A a = new A("A");
            B b = new B("A", "B", "C");
    
            System.out.println("A: " + a.hashCode());
            System.out.println("B: " + b.hashCode());
        }
    
    }
    

提交回复
热议问题