Unexpected output with HashMap
CODE:
开发者_StackOverflowpublic 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;
}
}
}
Actual Result:-
false
true
Expected Result:-
true
true
Why???
it's because of use NewMap
is IdentityHashMap
. Check documentation where is said
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.
EDIT:
Anyway I found a error in your code. void Puzzle23()
is not constructor it's a method. Constructor have to be defined without return value (e.g. Puzzle23()
). So you never fill map1
. When you fix this you realize that your output is false
false
because of IdentityHashMap
. When you switch map1
to HashMap
output will be true
true
as you expected. Anyway check documentation of IdentityHashMap
.
IdentityHashMap
uses ==
where ordinary HashMap
uses .equals()
. See documentation.
p22.map1.remove(new String(String1));
will not remove anything because NewMap
is a subclass of IdentityHashMap
.
Update
I was wrong
1) First error here is void
method disguised as constructor. That's why p22.map1
is always empty.
2) Second one is a NewMap
which is IdentityHashMap
. After 2 strings is added to it its size becomes 2 because while this strings are equal they are not identical (==
).
3) p22.map1.remove(new String(String1));
will not do anything as I said earlier.
精彩评论