简体   繁体   中英

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 do 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM