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

问个神奇的问题,重写了hashCode和equals,为什么Set还能添加重复的
废话不多说,上代码:
-----------------------------------------------
package mytest;

import java.util.HashSet;
import java.util.Hashtable;
import java.util.Set;

import org.junit.Test;

public class CollectionTest {

@Test
public void equalsTest() {

Set<Po> set = new HashSet<Po>();
Po po1 = new Po();
Po po2 = new Po();

set.add(po1);
set.add(po2);

System.out.println("po1.hashCode() == po2.hashCode() : " + (po1.hashCode() == po2.hashCode()));
System.out.println("po1.equals(po2) : " + po1.equals(po2));
System.out.println(set.size());

}
}

class Po {

private int id;
private String name;
private String value;

public int hashCode() {

return (id + name + value).hashCode();
}

public boolean equals(Po po) {

return this.hashCode() == po.hashCode()
&& this.getId() == po.getId()
&& this.getName() == null ? po.getName() == null : this.getName().equals(po.getName())
&& this.getValue() == null ? po.getValue() == null : this.getValue().equals(po.getValue());
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}


}

-------------------------------------
下面是运行结果
po1.hashCode() == po2.hashCode() : true
po1.equals(po2) : true
set.size() : 2

-----------------------------------
请问问题出在哪?


------解决方案--------------------
Java code

    @Override
    public boolean equals([color=#FF0000]Object o[/color]) {
        Po po = (Po)o;
        return this.hashCode() == po.hashCode()
        && this.getId() == po.getId()
        && this.getName() == null ? po.getName() == null : this.getName().equals(po.getName())
        && this.getValue() == null ? po.getValue() == null : this.getValue().equals(po.getValue());
    }