代码:
public class Puzzle23{
void Puzzle23(){
map1.put(String1, "1");
map1.put(String2, "2");
}
private final NewMap map1 = new NewMap();
private static final String String1 = new String("J2eeSig");
private static final String String2 = new String("J2eeSig");
public static void main(final String args[]){
final Puzzle23 p22 = new Puzzle23();
final Map<String, String> map2 = new HashMap();
map2.put(String1, "1");
map2.put(String2, "2");
System.out.println(p22.map1.size() == map2.size() ? true : false);
p22.map1.remove(new String(String1));
map2.remove(new String(String2));
System.out.println(p22.map1.size() == map2.size() ? true : false);
}
class NewMap extends IdentityHashMap<String, String>{
public void put(final String... values){
super.put(values[0], values[1]);
}
public int size(){
return super.size() + 1 - 1 / 1 * 1;
}
}
}
实际结果:-
false
true
预期结果:-
true
true
为什么???
最佳答案
因为使用NewMap
是IdentityHashMap
。检查说明的文档
This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.
编辑:
不管怎样,我在你的代码中发现了一个错误。 void Puzzle23()
不是构造函数,它是一种方法。必须在没有返回值的情况下定义构造函数(例如 Puzzle23()
)。所以你永远不会填写 map1
。当您修复此问题时,您会意识到由于 IdentityHashMap
,您的输出为 false
false
。当您将 map1
切换为 HashMap
时,输出将如您预期的那样为 true
true
。无论如何,请检查 IdentityHashMap
的文档。
关于java - HashMap 的意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5323533/