HashMap<Dog,String> map=new HashMap<Dog,String>();
map.put(new Dog("博美",23), "xyy");
map.put(new Dog("hhh",23), "hlh");
这是HashMap的代码,在Dog类中,实现了equals方法和hashcode()方法,如下:
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getAge();
result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
Animal other = (Animal) obj;
if (getAge() == other.getAge())
return true;
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
if (getName() == null) {
if (other.getName() != null)
return false;
} else if (!(getName()).equals(other.getName()))
return false;
return true;
}
这里可以看到,当两个Dog类的age相同时,应当代表是相同的,不放入hashmap中,为什么最后输出结果后HashMap依然有两个元素?求大神解答。。