简体   繁体   English

使用自定义类正确使用Hashtable

[英]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 . 输出为[DBG] false Why did Hashtable fail to register this element? 为什么Hashtable无法注册此元素? Does it have something to do with the way I try to pass a Pair to the hashtable? 它是否与我尝试将Pair传递给哈希表的方式有关?

You have to override hashCode() and equals(..) of your Pair class to indicate that two objects having the same numbers are equal. 您必须覆盖Pair类的hashCode()equals(..)以指示具有相同数字的两个对象相等。 (Better let your IDE generate these 2 methods for you.) (最好让IDE为您生成这两种方法。)

Hashtable uses hashCode() to determine the hash of the object and look it up. Hashtable使用hashCode()来确定对象的哈希并查找它。 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) 当您创建一个新的Pair实例时, Object的默认哈希实现会生成一个不同的哈希,因此您的Hashtable无法找到该对(在内部成功)

And finally - use a HashMap instead of Hashtable . 最后 - 使用HashMap而不是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) . 它是通过使用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. 第一个是你应该实现hashCode并且等于Pair类的方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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