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!

22 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?

Robert 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

nasha said...

Why was there no follow on bankruptcy then? The bailout of AIG FP went to (wow power leveling) hedge funds that bound credit swaps on Lehman failing or others betting on rating (wow power leveling) declines. AIG has drained over 100 billion from the government. Which had to go to (wow power leveling) those who bet on failures and downgrades. Many of whom (power leveling)were hedge funds. I-banks that had offsetting swaps needed the money from the AIG bailout or they would have been caught. Its an (wow powerleveling) insiders game and it takes just a little bit too much time for most people to think (wow gold) through where the AIG 100 billion bailout money went to, hedge funds and players, many of whom hire from the top ranks of DOJ, Fed, Treasury, etc. ZHANG XIAO CHEN

Affordable Luxurious Wedding Dress Blog said...

cheap wedding gowns,
discount bridal gowns,
China wedding dresses,
discount designer wedding dresses,
China wedding online store,
plus size wedding dresses,
cheap informal wedding dresses,
junior bridesmaid dresses,
cheap bridesmaid dresses,
maternity bridesmaid dresses,
discount flower girl gowns,
cheap prom dresses,
party dresses,
evening dresses,
mother of the bride dresses,
special occasion dresses,
cheap quinceanera dresses,
hot red wedding dresses

cheap wow gold said...

cheap wow gold buy wow power leveling my wow gold

cheap wow gold said...

MY wow gold CHEAPEST wow power leveling my gold wow

products said...

China Wholesalers has been described as the world’s factory. buy products wholesaleThis phenomenom is typified by the rise ofbusiness. Incredible range of products available with China Wholesale “Low Price and High Quality” not only reaches directly to their target clients worldwide but also ensures that wholesale from china from China means margins you cannot find elsewhere and China Wholesale will skyroket your profits.china wholesale productsbuy china wholesalewholesale chinawholesale productsbuy products

Adi said...

Oes Tsetnoc one of the ways in which we can learn seo besides Mengembalikan Jati Diri Bangsa. By participating in the Oes Tsetnoc or Mengembalikan Jati Diri Bangsa we can improve our seo skills. To find more information about Oest Tsetnoc please visit my Oes Tsetnoc pages. And to find more information about Mengembalikan Jati Diri Bangsa please visit my Mengembalikan Jati Diri Bangsa page and other update like as Beratnya Mengembalikan Jati Diri Bangsa, Mengembalikan Jati Diri Bangsa di perpanjang and Jangan Berhenti Mengembalikan Jati Diri Bangsa. Thank you So much.

Oes Tsetnoc | Lanjutkan Mengembalikan Jati Diri Bangsa

Adi said...

Oes Tsetnoc one of the ways in which we can learn seo besides Mengembalikan Jati Diri Bangsa. By participating in the Oes Tsetnoc or Mengembalikan Jati Diri Bangsa we can improve our seo skills. To find more information about Oest Tsetnoc please visit my Oes Tsetnoc pages. And to find more information about Mengembalikan Jati Diri Bangsa please visit my Mengembalikan Jati Diri Bangsa page and other update like as Beratnya Mengembalikan Jati Diri Bangsa, Mengembalikan Jati Diri Bangsa di perpanjang and Jangan Berhenti Mengembalikan Jati Diri Bangsa. Thank you So much.

Oes Tsetnoc | Lanjutkan Mengembalikan Jati Diri Bangsa

Gigi said...

Rolex Watches Rolex Watches
Tag Heuer Watches Tag Heuer Watches
rolex replica rolex replica
replica rolex replica rolex
rolex replica watches rolex replica watches
replica rolex watches replica rolex watches
Tag Heuer Tag Heuer
replica Tag Heuer replica Tag Heuer
Tag Heuer replica Tag Heuer replica
rolex rolex
rolex air king rolex air king
rolex datejust rolex datejust
rolex day date rolex day date
rolex daytona rolex daytona
rolex gmt rolex gmt
rolex submariner rolex submariner
rolex yachtmaster rolex yachtmaster
rolex air king watches rolex air king watches
rolex datejust watches rolex datejust watches
rolex day date watches rolex day date watches
rolex daytona watches rolex daytona watches
rolex gmt watches rolex gmt watches
rolex submariner watches rolex submariner watches
rolex yachtmaster watches rolex yachtmaster watches

arie 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..

AdFunds said...

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Acuvue Advance Astigmatism

dainfo said...

workout at home with dumbbells
at home workouts
lose weight at home
abs workout at home
exercise machines at a gym
chest workout at home
get fit with exercise
how to exercise at home
run a marathon to shed pounds and improve cardio
how to lose weight at home
a healthy heart comes with exercise
medicine ball abs
fatigue your muscles by using weights or your body
upper body workout at home
be sure to hydrate your muscles as often as possible
dandruff home remedy
Good share you have here hope you keep it up, and don't forget to use dumbbells while exercising, even better though you can do these lose weight at home
where to buy venapro
buy venapro
venapro
venapro reviews
venapro review
best tooth whitening system
bleaching your teeth
teeth bleaching products
teeth bleaching trays
tooth whitening bleach

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.

Jerry Gene 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