views:

54

answers:

2

This piece of code generates unexpected output.

Hashtable<Pair, Integer> results = new Hashtable<Pair, Integer>();
results.put(new Pair(0, 1), 2);
System.out.println("[DBG] " + results.containsKey(new Pair(0, 1)));

The output is [DBG] false. Why did Hashtable fail to register this element? Does it have something to do with the way I try to pass a Pair to the hashtable?

+7  A: 

You have to override hashCode() and equals(..) of your Pair class to indicate that two objects having the same numbers are equal. (Better let your IDE generate these 2 methods for you.)

Hashtable uses hashCode() to determine the hash of the object and look it up. When you create a new Pair instance, the default hashing implementation of Object generates a different hash, and hence your Hashtable fails to locate the pair (which is successfully inside)

And finally - use a HashMap instead of Hashtable . It's a newer and better implementation of the concept, and does not have unnecessary synchronization.

Bozho
(And use `@Override` to avoid attempting to override the likes of `hashcode()` or `equals(Pair)`.)
Tom Hawtin - tackline