Java Hashtable.contains() 错误
我正在使用最新版本的 x64 Java。
java version "1.6.0_24"
Java(TM) SE Runtime Environment (build 1.6.0_24-b07)
Java HotSpot(TM) 64-Bit Server VM (build 19.1-b02, mixed mode)
我发现哈希表有不良行为。这是一个截取的代码示例:
public class Test {
public static void main(String[] args) {
Hashtable<MyObject, MyObject> table =
new Hashtable<MyObject, MyObject>();
MyObject myObj = new MyObject();
System.out.println(myObj.hashCode());
System.out.println(myObj.equals(myObj));
if (!table.contains(myObj)) {
System.out.println("OK");
table.put(myObj, myObj);
}
if (!table.contains(myObj)) {
System.out.println("ERROR");
System.out.println(table);
}
}
}
这是输出:
1500
true
OK
ERROR
{"myObject"="myObject"}
有任何线索它为什么会这样吗?有人能指出这个问题吗?顺便说一句,当我使用 HashSet() 做同样的事情时,我没有得到不需要的效果。
I am using the latest version of Java for x64.
java version "1.6.0_24"
Java(TM) SE Runtime Environment (build 1.6.0_24-b07)
Java HotSpot(TM) 64-Bit Server VM (build 19.1-b02, mixed mode)
I found out that the Hashtable has undesired behavior. Here is a snipped code example:
public class Test {
public static void main(String[] args) {
Hashtable<MyObject, MyObject> table =
new Hashtable<MyObject, MyObject>();
MyObject myObj = new MyObject();
System.out.println(myObj.hashCode());
System.out.println(myObj.equals(myObj));
if (!table.contains(myObj)) {
System.out.println("OK");
table.put(myObj, myObj);
}
if (!table.contains(myObj)) {
System.out.println("ERROR");
System.out.println(table);
}
}
}
Here is the output:
1500
true
OK
ERROR
{"myObject"="myObject"}
Any clue how come it behaves that way? Can someone point to the problem? By the way, when I am doing the same using HashSet(), I do not get the undesired effect.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Hashtable 工作得很好,但不受欢迎,在 Java 1.2 (1998) 中被 HashMap 取代,我建议你不要使用它,除非必须。
打印
但是更好的解决方案是使用像 HashMap 这样的 Map。
Hashtable works just fine but is undesirable was replaced by HashMap in Java 1.2 (1998) I suggest you not use it unless you have to.
prints
however a better solution would be to use a Map like HashMap.