【问题标题】:HashMap does not give expected outputHashMap 没有给出预期的输出
【发布时间】:2016-08-31 12:59:38
【问题描述】:

我在下面提到的代码中添加了一些 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();
    }
}

【问题讨论】:

标签: java collections hashmap equals hashcode


【解决方案1】:

hashcode()方法名错误,应该是hashCode()

【讨论】:

  • 如果你用@Override注释你的重写方法,编译器会帮助你注意到这个错误。
【解决方案2】:

你的 hashcode() 方法名有误,改成 hashCode()。

详情请看代码

class Dog {

    private String name;

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

    @Override
    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;
        }
    }

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-18
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 2019-07-16
    相关资源
    最近更新 更多