HashMap没有给出预期的输出

时间:2016-08-31 12:59:38

标签: java collections hashmap equals hashcode

我在下面提到的代码中添加了一些Dog对象。 我已经实现了equals和hashcode方法。 然后在尝试获取Dog对象的值时,我得到了这个输出

5
Third

运行此代码时,输​​出为

5
null

这是代码

import java.util.HashMap;

public class MapTest {

    public static void main(String[] args) {

        HashMap<Dog, String> map = new HashMap<Dog, String>();

        Dog d1 = new Dog("Tiger");
        Dog d2 = new Dog("Tommy");
        Dog d3 = new Dog("Jackie");
        Dog d4 = new Dog("Sheru");
        Dog d5 = new Dog("Rahul");

        map.put(d1, "First");
        map.put(d2, "Second");
        map.put(d3, "Third");
        map.put(d4, "Fourth");
        map.put(d5, "Fifth");

       System.out.println(map.size());
       System.out.println(map.get(new Dog("Jackie")));
    }
}

class Dog {

    private String name;

    public Dog(String name) {
        this.name = name;
    }

    public boolean equals(Object obj) {
        System.out.println("inside equals");
        if ((obj instanceof Dog) && this.name.equals(((Dog) obj).name)) {
            return true;
        } else {
            return false;
        }
    }

    public int hashcode() {
        return this.name.hashCode();
    }
}

2 个答案:

答案 0 :(得分:4)

hashcode()方法名称错误,应为hashCode()

答案 1 :(得分:0)

您的hashcode()方法名称错误,并将其设为hashCode()。

详情请参阅代码

value match {
    case Expr(lhs, rhs) => // do x
    case Atomic(a) => // do y
    case _ => // optional, but will throw exception if something cannot be matched whereas switch won't
}