日期:2014-05-20  浏览次数:20715 次

重写equals和hashcode时用到的属性必须一致么???
Java code

class People {
    private String name;
    private int age;

    public People(int age, String name) {
        super();
        this.age = age;
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        People other = (People) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
}


问题:
1.equals和hashcode只要重写其中一个,从业务上是否要求一定要重写另一个?否则何种情况会有弊端
2.如果同时重写两者,是否两者用到的属性必须一致,而不能一个多某个属性,一个少?
3.何种情况可以单独用其中一个,而没有副作用?

------解决方案--------------------
1、没有,但推荐是都要写,否则可能equals相等但hashcode却不相等的情况而导致比较出现错误;
2、不需要,hashcode关注性能,equals关注比较可观性;
3、当你确定你不会使用任何公共或其它组件包处理你定义的类时。
------解决方案--------------------
从原则上来说,如果实现equals,需要重写hashcode,因为如果a.equals(b)返回为true的话,就必须a.hashcode()==b.hashcode()也返回true (反之也是一样)。
因为一些组件比较是用hashcode而不是equals方法。例如hashMap的实现,以及一些对象比较大小的默认实现。如果你以后做到系统架构与分析的职责的时候,在做高性能通用组件,用到hashcode的比率就会逐渐的增加。