开发者

Correct use of Hashtable with custom class

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 d开发者_StackOverflowo with the way I try to pass a Pair to the hashtable?


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.


it is caused by creating two different object by using new Pair(0,1). So you have two choises for getting true :

The first one is you should implement hashCode and equals methods of Pair class.

The second one use same object like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜