Possible Duplicate:
Overriding equals and hashCode in Java




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;  }
     */
}


输出是

testpack.TestEm@3e8
testpack.TestEm@7d0
testpack.TestEm@bb8
emp3


嗨,我在TestEm类中重写了Object类的某些方法,一切正常,但是前三个输出使用迭代器,然后执行SOP,最后一个简单地使用SOP,我只想知道为什么前三个输出是作为使用迭代器的对象,第四个对象只是将正确的输出作为与键对应的值,我没有覆盖toString(),因此前三个输出是正确的,但是没有toString()时,SOP如何显示正确的输出。

最佳答案

迭代器遍历集合中的对象,而

map.get(new TestEm("ghi", 300))


返回与上述键关联的值。该值为"emp3"

10-04 10:30