重写 equals() 和 hashcode()

重写equals()

@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name);
    }

 

 @Override
    public int hashCode() {

//以下注释重写过程可以根据自己代码的类属性进行组织。未注释的为源码部分 // final int prime = 31; // int result = 1; // result = prime * result + age.hashCode(); // result = prime * result + ((name == null) ? 0 : name.hashCode()); // return result; return Objects.hash(name, age);

 

    public static int hash(Object... values) {
        return Arrays.hashCode(values);
    }

  

public static int hashCode(Object a[]) {
        if (a == null)
            return 0;

        int result = 1;

        for (Object element : a)
            result = 31 * result + (element == null ? 0 : element.hashCode());

        return result;
    }

  

 

原文地址:https://www.cnblogs.com/Andrew520/p/11031530.html