即使字符串和哈希码不同,Java Hashtable .containsKey(String key)也返回true ...如何? [英] Java Hashtable .containsKey(String key) is returning true even when the strings and hashcodes are different... How?

查看:273
本文介绍了即使字符串和哈希码不同,Java Hashtable .containsKey(String key)也返回true ...如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在java中遇到了Hashtable的一些问题,其中FEightPuzzle是我创建的一个类。

I'm currently having some issues with my Hashtable in java, where FEightPuzzle is a class which I've created.

在我的课程中我有一个String存储每个实例的密钥。现在在我的程序中,当我在Hashtable中检查重复的实例时,我有时会找到一些真正找到的实例。

Inside my class I have a String which is storing the key for each instance. Now during my program when I check inside the Hashtable for duplicate instances I sometimes "find" some when really the found ones are different.

例如当我调用bol时。 containsKey(current.key)其中bol是HT,current是FEightPuzzle。

Take for example when I call bol.containsKey(current.key) where bol is a HT and current is an FEightPuzzle.

如果这是真的,我检查按键的值,它们是

When this is true I check the values of the keys and they are

current.key =
"8 14 11 0 6 12 13 1 10 4 5 9 15 2 3 7"

bol.get(current.key).key =
"12 8 4 0 13 9 5 1 14 10 6 2 15 11 7 3"

with值

current.key.hashCode() = -950607924

bol.get(current.key).key.hashCode() = -1856769042

很抱歉打扰你,但这个问题是我真的很想找到我,这是我今晚最后一次诚实的预测(你不喜欢那样)......任何提示或答案都会非常感激!

I'm sorry to bother you but this problem is really getting to me, and it was the last thing I expected tonight to be honest (don't you love that)... Any hints or answers would be greatly appreciated!

推荐答案

我已经重读了你的问题,据我了解你有以下问题:

I've reread your question, and as I understand it you have the following problem:

你做了

bol.containsKey(current.key)

检查当前是否已经在 bol

什么时候返回true,您希望 current.key 映射到的值确实应该是 current ,但是作为您的哈希 - 代码表明,它不是。

When it returns true, you expect that the value mapped to by current.key should indeed be current, but as your hash-codes indicate, it's not.

问题可能是以下之一:


  1. 你没有把拼图对象放在哈希表中。

  1. You didn't put the puzzle object in the hashtable correctly in the first place.

你应该这样做

bol.put(somePuzzle.key, somePuzzle)


  • 当拼图在地图中时,您更改了密钥。这是不允许的。

  • You changed the key when the puzzle was in the map. THIS IS NOT ALLOWED.

    在地图中添加条目后,如果不删除/重新插入映射,则可能无法更改密钥。

    Hashtable将根据您在插入时提供的密钥查找对象。

    The Hashtable will look for the object, based on the key you provided when inserting.

    您不小心为多个不同的拼图对象提供了相同的密钥(在这种情况下,一个 put 将覆盖前一个)

    You've accidentally provided the same key for multiple different puzzle objects (in which case, one put will override a previous one)






    一个建议是让FEightPuzzle覆盖hashCode和equals并使用HashSet而不是Hashtable。


    One suggestion would be to let FEightPuzzle override hashCode and equals and use a HashSet instead of a Hashtable.

    这篇关于即使字符串和哈希码不同,Java Hashtable .containsKey(String key)也返回true ...如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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