Java Hashtable .containsKey(String key) is returni

2019-06-06 06:35发布

问题:

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

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.

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 values

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!

回答1:

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.



回答2:

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).