public class Test
{
public static void main(String[] args) {
Employee e1=new Employee(1);
Employee e2=new Employee(1);
HashMap<Employee,String> map=new HashMap<Employee,String>();
map.put(e1, "A");
map.put(e1, "B");
map.put(e2, "C");
}
}
class Employee{
private int id;
Employee(int id){
this.id=id;
}
@Override
public int hashCode() {
System.out.println("hascode is ="+this.id);
return this.id;
}
@Override
public boolean equals(Object obj) {
System.out.println("Equals");
return super.equals(obj);
}
}
当我再次放置相同的对象e1时,equals()方法不会被调用,那么如何在不检查映射中现有对象的情况下替换键e1的值B?(我认为这是equals方法的工作)
map.put(e1, "B")
,您只是用新字符串简单地覆盖了该键及其值。为什么您会期望需要equals()
或hashcode()
呢? - Tim Biegeleisen