Tuesday, February 21, 2017

fun with IdentityHashMap

fun with IdentityHashMap


What does this program print? (Eliding the generics so you can read it.)

public static void main(String[] args) {
Map m = new IdentityHashMap();
m.put("a", 1);
m.put("a", 2);
m.put("a", 3);
System.out.println(new HashSet(m.entrySet()).size());
}


When youve got the answer, scroll down...






























The answer is 1. Even though this is an identity-based HashMap, String literals are interned, so after the first entry is created, it is overwritten two times leaving a map of size one. This single entry will then be placed into the HashSet, so the HashSet has size one.

If you got it right, congrats. Now lets make a small change.

public static void main(String[] args) {
Map m = new IdentityHashMap();
m.put("a", 1);
m.put("b", 2);
m.put("c", 3);
System.out.println(new HashSet(m.entrySet()).size());
}


Now what does it print?

Once youve decided on your answer, compile and run the code (sorry about the warnings). Were you right?

Update: Ok, this isnt doing the same thing for yall that it was doing for me. And now its not doing it for me either. :) Ok look. Try this: remove the call to .size(). Just print out the entry set itself. Guess what its going to be first. Then see. Itll be worth it, really!

Available link for download