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

equals()方法的覆盖问题
大家知道,equals()方法未覆盖时,仅当两个比较的引用指向同一对象时,返回true。  
最近看到一本书说,只要覆盖equals()方法,就应该覆盖hasCode()方法。
谁能举例说明到底是怎么回事!

------解决方案--------------------
public class A {
public static void main(String[] args) {
A a = new A();
A.B b = a.new B( "vagrant ", "0001 ");
A.B c = a.new B( "vagrant ", "0001 ");

Map map = new HashMap();
map.put(b, b);
map.put(c, c);
// 注掉hashCode方法比较执行结果
System.out.println(map.size());
}

public class B {
public B(String name, String id) {
this.name = name;
this.id = id;
}
private String name;
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public boolean equals(Object o) {
if (o == this) return true;
if (! (o instanceof B)) return false;
B ob = (B)o;
return this.name.equals(ob.name) && this.id.equals(ob.id);
}

public int hashCode() {
int result = 37;
result += this.name.hashCode() * 17;
result += this.id.hashCode() * 17;
return result;
}
}
}
------解决方案--------------------
不一定需要覆盖的.....

覆盖hashcode类主要用要set集合里面..

在set集合中为了确保集合元素的唯一性,集合中没有重复的元素,插入的时候会用equals()方法按照内存地址来比较对象是否相等,当你的equals()方法没有被覆盖时,比较得出两个object地址为true,其哈希码一定也相同,

当你覆盖了equals()方法的,可能你比较出来的equals()结果是true,但两个object的在内存中存放地址不同,哈希码可能会不同,这就的话hashset这个就无法正常运行,所以为了保证HashSet正常工作,这时要同时覆盖HashCode()方法....