HashMap不基于键返回值

阿特鲁斯

我正在尝试将HashMap与我的班级Cell用作键。但是,将项目放入HashMap后,对该项目的调用contains将返回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)));
}

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

bstempi

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

您使用两个单独的地址创建了两个单独的对象。没有这些方法,JVM将无法知道对象是“相同的”。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章