简体   繁体   English

Java Hashtable.contains()错误

[英]Java Hashtable.contains() error

I am using the latest version of Java for x64. 我正在使用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)

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. 顺便说一句,当我使用HashSet()进行相同操作时,不会得到不想要的效果。

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. Hashtable可以正常工作,但是不希望被Java 1.2(1998)中的HashMap取代。我建议除非必要,否则不要使用它。

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

static class MyObject { }

prints 版画

1584673689
true
OK

however a better solution would be to use a Map like HashMap. 但是更好的解决方案是使用像HashMap这样的Map。

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

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