import java.util.HashMap;
/**
* 验证即使有了equals,还需要hashcode的情况
* @author microsoft
*
*/
public class Person {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public static void main(String args[]) {
Person p = new Person();
p.id = "123";
Person pp = new Person();
pp.id = "321";
HashMap map = new HashMap();
map.put(p, "p1");
map.put(pp, "p2");
Person pNew = new Person();
pNew.id = "123";
System.out.print(map.get(pNew));
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if(this==obj) return true;
if(!(obj instanceof Person)){
return false;
}
return ((Person)obj).id.equals(id);
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return Integer.parseInt(this.id);
}
}
display result is:"p1"
if no funcation hashCode() ,the result is null;
if no funcation equals(),the result alse is null;
so for the right result,these two funcations "equals()" and "hashcode()" is needed.