我使用java.util.IdentityHashMap
进行了测试,请参阅
public class IdentityHashMapTest{
public static void main(String args[]) {
Map<String, String> m = new IdentityHashMap<String, String>();
m.put("John", "Doe");
m.put("John", "Paul");
System.out.println(m.size());
}
}
根据Java API所说,
This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values)
结果可能是2
。但实际是1
。 IdentityHashMap 类是否错误?
最佳答案
更改为
m.put("John", "Doe");
m.put(new String("John"), "Paul");
它将有两个条目。字符串文字是池化的,因此 "John"== "John"
。
关于java - IdentityHashMap 类是否错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12213877/