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("开发者_Python百科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.
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.
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.
精彩评论