集合中Set_List必须覆盖 hashCode()与 equals()

集合中Set_List必须覆盖    hashCode()与    equals()

    
    @Override
    public int hashCode() {
        System.out.println("=====================hashCode()");
        
        // 用一个和该对象相关的基数 * 31的系数,这样得到的结果比较接近hash算法的结果
        return (this.height + this.name.hashCode() + this.sex.hashCode() + this.bithday
                .hashCode()) * 31;
    }

    @Override
    public boolean equals(Object obj) {
        System.out.println("=====================equals()");
        if (this == obj) {
            return true;
        }

        if (obj instanceof Student) {
            Student stu = (Student) obj;
            if (this.height == stu.height && this.name.equals(stu.name)
                    && this.sex.equals(stu.sex)
                    && this.bithday.equals(stu.bithday)) {
                return true;
            }
        }

        return false;
    }
原文地址:https://www.cnblogs.com/chen-lhx/p/4426005.html