Friday, May 13, 2011

Java Puzzlers@Google I/O

Josh Bloch and I gave one of his Java Puzzlers talk at Google I/O this year. If you hate Java, you can waste a perfectly good hour listening to us make unfunny jokes at its expense.


Jeffrey Yasskin said...

In several languages, if you manage to change the value of an object once it's inside a set, you cause the set to do all sorts of wacky things, since its internal invariants get messed up. In a Java HashSet, I would have expected Map.Entry(Male, Male) and Map.Entry(Female, Female) to have different hash values and so wind up in different buckets, even if it was the same object in each of the two buckets. Is that guess wrong, or what intervenes later to bring the size back down to 1?

Jeremy Manson said...

Here, we cheated a bit. The hashcode for the map entry is the XOR of the key's hashcode and the value's hashcode. When the key and the value are the same (as in, MALE == MALE and FEMALE == FEMALE), the hash codes for both are 0. As a result, they end up in the same bucket.

That's probably a good basis for another puzzler.