【发布时间】:2014-11-26 10:57:24
【问题描述】:
以下代码示例的输出为:
{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}
【问题讨论】:
标签: java hashmap equals hashcode