以下代码示例的输出是:
{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}
事实上,你搞反了。该值被覆盖。到目前为止,钥匙还没有更换过HashMap
就而言,e 和 e2 是相同的。
你的输出是{1--e=e2, 2--e1=e1}
:
key = e, value = "e2" (which overrode the old value "e")
key = e1, value = "e1"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)