以下代码示例的输出是:
{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,但不能覆盖值。以我的理解,输出应该是:
e2
e
{1–e2 = e2,2–e1 = e1}
实际上,您将其倒退了。该值被覆盖。密钥没有被替换,因为就HashMape和e2而言,它们是相同的。
HashMap
您的输出是{1--e=e2, 2--e1=e1}:
{1--e=e2, 2--e1=e1}
key = e, value = "e2" (which overrode the old value "e") key = e1, value = "e1"