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.
Java中equals与hashCode的重要性
本文通过一个Java示例说明了在使用HashMap时,正确实现equals()和hashCode()方法的重要性。当两个对象相等时(根据equals()判断),它们应该返回相同的哈希码,以确保在散列表中能够正确地存储和检索这些对象。
345

被折叠的 条评论
为什么被折叠?



