以下代码示例的输出是:
{1--e=e2, 2--e1=e1}
package com.sid.practice;
import java.util.HashMap;
import java.util.Map;
public class InputOutputPractice
{
public InputOutputPractice()
{
}
public static void main(String[] args)
{
Employee e = new InputOutputPractice().new Employee(1, "e");
Employee e1 = new InputOutputPractice().new Employee(2, "e1");
Employee e2 = new InputOutputPractice().new Employee(1, "e2");
Map m = new HashMap();
m.put(e, "e");
m.put(e1, "e1");
m.put(e2, "e2");
System.out.println(m);
}
class Employee
{
public Employee(int id, String name)
{
this.id=id;
this.name = name;
}
private int id;
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
@Override
public boolean equals(Object obj)
{
return ((Employee)obj).getId()==(this.getId());
}
@Override
public int hashCode()
{
return Integer.valueOf(getId()).hashCode();
}
@Override
public String toString()
{
return this.id + "--" + this.name;
}
}
}
我不明白对象 e2
如何能够覆盖对象 e
中的键,而不是值。根据我的理解,输出应该是:
{1--e2=e2, 2--e1=e1}
最佳答案
实际上,你搞反了。该值已被覆盖。 key 没有被替换,因为就 HashMap
而言,e 和 e2 是相同的。
您的输出是 {1--e=e2, 2--e1=e1}
:
key = e, value = "e2" (which overrode the old value "e")
key = e1, value = "e1"
关于Java HashMap 返回值不符合我对 equals 和 hashcode 的理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27147325/