HashMap不返回基于键的值 [英] HashMap not returning values based on key

查看:95
本文介绍了HashMap不返回基于键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用我的class Cell作为key来使用HashMap。但是,将项目放入HashMap之后,包含该项目的调用将返回false。

  public static void main(String args []){
HashMap< Cell,String> map = new HashMap< Cell,String>();
map.put(new Cell(0,0),Bob);
System.out.println(map.containsKey(new Cell(0,0)));
System.out.println(new Cell(0,0).equals(new Cell(0,0)));





$ b

这会输出false和true,它应该打印true和true,因为根据Map文档containsKey使用.equals()。我做错了什么?

解决方案

这很可能是因为您没有 equals() 执行了hashCode()。在Java中,经验法则是如果你实现了一个,你必须实现另一个。在你的情况下,它是强制性的,因为 HashMap 使用它们。



你创建了两个单独的对象, 。没有这些方法,JVM无法知道对象是相同的。



请参阅 http://docs.oracle.com/javase/7/docs/api/java/lang/Object .html#hashCode()


I'm trying to use a HashMap with my class Cell as the key. However, after putting an item into the HashMap, calling contains on the item will return false.

public static void main(String args[]) {
        HashMap<Cell, String> map = new HashMap<Cell, String>();
        map.put(new Cell(0,0), "Bob");
        System.out.println(map.containsKey(new Cell(0,0)));
        System.out.println(new Cell(0,0).equals(new Cell(0,0)));
}

This prints out false and true, where it should print true and true, since according to the Map docs containsKey uses .equals(). What am I doing wrong?

解决方案

This is most likely because you don't have equals() and hashCode() implemented. In Java, the rule of thumb is that if you implement one, you must implement the other. In your case, it's mandatory because HashMap makes use of them.

You created two separate objects with two separate addresses. Without these methods, the JVM has no way of knowing that the objects are "the same."

See http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()

这篇关于HashMap不返回基于键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆