Fooled by Java identity
[ joehni ] 14:55, Saturday, 27 January 2007

How often do you imply facts that nowhere have been stated or confirmed? Last week I found myself trapped by such a certainty that revealed to be a false assumption.

Ever asked yourself what you can expect from the values delievered by the JDK's method System.identityHashCode(Object object) ? My original believe (and I suppose I am not alone here) was that the value reflects somehow the memory address of the given object. Not that I tried to access the object in any obscure way, it was just based on the fact that there are not a lot of more things to assign an identity to an object - implying that identity has something to do with uniqueness for the object's lifetime.

Well, the implication was wrong. Short unit test:

Map identityMap = new HashMap();
for(int i = 0; i < 50000; ++i) {
    String s = "JUnit " + i;
    identityMap.put(new Integer(System.identityHashCode(s)), s);
}
assertEquals(50000, identityMap.size());
Output:
junit.framework.AssertionFailedError: expected:<50000> but was:<49963>

Bottom line: The identity hash code of an object does not mean uniqueness. And have a closer look at the (short) Javadoc of System.identityHashCode() — uniqueness is nowhere stated


Comments
Post a comment









Remember personal info?