public boolean equals(Object obj) public int hashCode()理解这两方法之间的区别联系是非常重要的,特别是当用户自定义的对象被添加到Map中。然而,即使高级开发人员有时无法弄清楚他们应该如何正确使用。在这篇文章中,我会先给大家看一个常见的错误的例子,然后解释如何的equals()和hashCode()之间的区别联系。
import java.util.HashMap;
public class Apple {
private String color;
public Apple(String color) {
this.color = color;
}
public boolean equals(Object obj) {
if (!(obj instanceof Apple))
return false;
if (obj == this)
return true;
return this.color.equals(((Apple) obj).color);
}
public static void main(String[] args) {
Apple a1 = new Apple("green");
Apple a2 = new Apple("red");
//hashMap stores apple type and its quantity
HashMap<Apple, Integer> m = new HashMap<Apple, Integer>();
m.put(a1, 10);
m.put(a2, 20);
System.out.println(m.get(new Apple("green")));
}
}public int hashCode(){
return this.color.length();
}
Java中equals()和hashCode()的区别与联系,布布扣,bubuko.com
Java中equals()和hashCode()的区别与联系
原文:http://blog.csdn.net/sunling_sz/article/details/21707987