java - HashMap 没有给出预期的输出

标签 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();
    }
}

最佳答案

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

关于java - HashMap 没有给出预期的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39250367/

相关文章:

java - 收集对 JDBC 对象的引用并在循环中关闭它们是否安全?

java - RecyclerView 内的 CardView 在扩展时未调整到正确的高度

java - 在 Android 上使用 List<String> 发出警告

Java 集合 - 前 n 个和后 n 个元素

java - Hadoop 的输入和输出如何工作?

c# - 可以使用 int 作为 KeyedCollection 中的键吗

java - 从迭代器的 next 方法中获取 ClassCastException

java - Java 8 中带流的字符串集到 HashMap

Java 表模型 hashmap 与 list

存储在 HashMap 中的 Java 泛型 Pair<String, String> 未正确检索键-> 值