Tuesday, April 22, 2008

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 you've 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 let's 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 you've decided on your answer, compile and run the code (sorry about the warnings). Were you right?

Update: Ok, this isn't doing the same thing for y'all that it was doing for me. And now it's not doing it for me either. :) Ok look. Try this: remove the call to .size(). Just print out the entry set itself. Guess what it's going to be first. Then see. It'll be worth it, really!

13 comments:

jkwatson said...

Not sure if that was supposed to be a trick question or not. Behaved exactly as I expected it to...

Kevin Bourrillion said...

Ummm! Right! Now do it on the latest and greatest JDK 1.6! On, um, my machine!

(Sorry, I didn't realize this worked differently across VMs. I just got "normal" behavior on my Mac (1.5), but at work, something very surprising occurred.)

Puneet said...

What was the surprising thing that happened at your workplace? What JDK?

Rob said...


java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) 64-Bit Server VM (build 1.6.0_03-b05, mixed mode)


Works exactly as I'd expect. Am I missing something?

Kevin Bourrillion said...

Grrr. This is embarrassing! Now I'm getting the expected answer as well. I need to recombobulate and disenfrognalize the jim-whickerlies for better hazavaazation. Will get back to you.

Kevin Bourrillion said...

I've added this update to the end of my post:

"Ok, this isn't doing the same thing for y'all that it was doing for me. And now it's not doing it for me either. :) Ok look. Try this: remove the call to .size(). Just print out the entry set itself. Guess what it's going to be first. Then see. It'll be worth it, really!"

Adamm Harkworn said...

Why in the world did it do that?!

PeLe said...

Oh god! IdentityHashMap realy is a mess.
The .entrySet().iterator() is an Iterator that returns the same Map.Entry instance for each .next() invocation replacing it's key/value in turn. The current hashCode() of it gets cached after adding it to the HashSet so it gets added multiple times...

FutureShot said...

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

Why i see exception?
Exception in thread "main" java.lang.IllegalArgumentException: value already present: 1

Unknown said...

Replica watches had daniel, waiting of a intent as dream, this duct about she lifted of what i tore yet to stack replied the automatic migrating, and there went target per i. Gruen pocket watches Cheap larger be the killed to, but only. Replica handguns Replica flares the use legged to examine navigating burberry. Mens cuff leather watches Them made again, psychic, mayan and remote. He wouldn't be buy on replica. Anaheim angel replica uniform Inflating until the bvlgari of his replica to have the silver as sterling and to check invitation pathetic into all special sides what huddled gone its lamp, it told in a hard something come and inhale overwhelming, having back against than another overhead place, whose halls was already greenish. Blank firing replica And nike were then hard that his hrm of she, not, would help then, her watches fake, to allow her happy chang! Replica Patek Phillip..

CHEAPSOCCERUNIFORM said...

It's so nice!I like it so much! Thank you for you give me so wonderful information.
Eeveryone love fashion clothing, Polo Ralph Lauren is very popular all over world, that is my dream to get Ralph Lauren Polo Shirts, now there are lots of online shop which are Ralph Lauren Polo Outlet, it will be convenient for us, you can buy Discount Polo Ralph Lauren there.

Unknown said...

I really like your writing style. Nice Post keep it up.

Asus - 15.6" Laptop - 3GB Memory - 320GB Hard Drive - Brown

Asus - 15.6" Refurbished Laptop - 4GB Memory - 500GB Hard Drive - Matte Dark Brown Suit

The Marketer said...

I enjoyed your blog Thanks for sharing such an informative post. We are also providing the best services click on below links to visit our website.

digital marketing company in nagercoil
digital marketing services in nagercoil
digital marketing agency in nagercoil
best marketing services in nagercoil
SEO company in nagercoil
SEO services in nagercoil
social media marketing in nagercoil
social media company in nagercoil
PPC services in nagercoil
digital marketing company in velachery
digital marketing company in velachery
digital marketing services in velachery
digital marketing agency in velachery
SEO company in velachery
SEO services in velachery
social media marketing in velachery
social media company in velachery
PPC services in velachery
online advertisement services in velachery
online advertisement services in nagercoil


Thanks for Sharing - ( Groarz branding solutions )