import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
class Employee{
int id;
Employee(int id){
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int hashCode(){
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public boolean equals(Object obj){
return EqualsBuilder.reflectionEquals(this, obj);
}
}
public class P2 {
public static void main(String[] args) {
Employee emp1 = new Employee(10);
Employee emp2 = new Employee(10);
Employee emp3 = new Employee(14);
HashMap<Employee,String> emp = new HashMap();
emp.put(emp1, "Employee1");
emp.put(emp2, "Employee2");
emp.put(emp3, "Employee3");
Set set = emp.keySet();
Iterator it = set.iterator();
while(it.hasNext()){
Employee empl = (Employee)it.next();
System.out.println(emp.get(empl));
}
System.out.println(emp.containsKey(emp1));
System.out.println(emp1.equals(emp2));
System.out.println(emp.get(emp1));
}
}
輸出插入後存在: -HashMap的 - 以前的主要新相等的對象
Employee2
Employee3
true
true
Employee2
這裏EMP1和EMP2是相等的對象。前2個輸出表示我們在hashmap中有2個入口(不是3個)。當我們在hashmap中插入第二個對象(emp2)時,它將刪除先前的條目,即emp1。但是第三個輸出表示hashmap仍然包含關鍵字emp1和第五個輸出,說明關鍵字emp1和emp2指向hashmap中的相同條目。我對hashmap的這種行爲感到困惑,即條目已經消失,但是鍵仍然存在,並指向下一個相等的對象。
提示您的emp1和emp2都有相同的ID(10)! – Sikorski
對於一個新手來說很好的輸入... – GhostCat