package testpack;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class TestEm {
private String company;
private int salary;
TestEm(String company, int salary) {
this.company = company;
this.salary = salary;
}
public static void main(String[] args) {
Map<TestEm, String> map = new HashMap<TestEm, String>();
map.put(new TestEm("abc", 100), "emp1");
map.put(new TestEm("def", 200), "emp2");
map.put(new TestEm("ghi", 300), "emp3");
Set<TestEm> set = map.keySet();
Iterator<TestEm> it = set.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
**System.out.println(map.get(new TestEm("ghi", 300)));**
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof TestEm))
return false;
TestEm te = (TestEm) o;
return te.company.equals(company) && te.salary == salary;
}
@Override
public int hashCode() {
int code = 0;
code = salary * 10;
return code;
}
/*
* @Override public String toString() {
*
* return this.company; }
*/
}
输出是
测试包.TestEm@3e8 测试包.TestEm@7d0 测试包.TestEm@bb8 emp3
嗨,我在我的 TestEm 类中重写了 Object 类的一些方法,一切都很好,但是前三个输出使用迭代器,然后执行 SOP,最后一个只是使用 SOP,我只想知道为什么前三个输出是作为使用迭代器的对象,第四个只是作为与键对应的值的正确输出,我没有覆盖 toString() 所以前三个输出是正确的,但是没有 toString() SOP 如何显示正确的输出。