Java Hashtable .containsKey(String key) is returning true even when the strings and hashcodes are different… How?

↘锁芯ラ 提交于 2019-12-08 14:05:37

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

You do

bol.containsKey(current.key)

to check if current is already in bol.

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.

The problem is likely to be one of the following:

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

    You should do

    bol.put(somePuzzle.key, somePuzzle)
    
  2. You changed the key when the puzzle was in the map. THIS IS NOT ALLOWED.

    After you've added the entry in the map, you may not change the key without removing / reinserting the mapping.

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

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


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

I think perhaps you're misunderstanding what Hashtable does. It maps keys to values. So calling get(key) on your key is going to return the value you provided with put(key, value). Now if you're always putting the same value in as the key you should expect the same thing, however in that case all you need is a HashSet. If you're putting the same values in for different keys, it is going to allow that. Only the keys are unique in a Hashtable (and HashMap is the same).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!