Skip to content

Instantly share code, notes, and snippets.

@chilmers
Created April 2, 2012 11:30
Show Gist options
  • Save chilmers/2282814 to your computer and use it in GitHub Desktop.
Save chilmers/2282814 to your computer and use it in GitHub Desktop.
Boxing/unboxing problem with Integer equality
import org.junit.Test;
import junit.framework.Assert;
public class IntTest {
@Test
public void testSame() {
Assert.assertSame(100,100);
// Since assertSame takes two Objects, the two ints will be boxed to Integers.
// The JVM has an object pool of predefined Integers which will be used for Integers < 128,
// while an Integer >= 128 will be created as a new Integer in the memory, thus the == operator won't work.
// I.e. the below will not work since 200 > 127 which is not in the JVM object pool for Integers.
Assert.assertSame(200,200);
}
@Test
public void testBoxingIntegers() {
for (Integer i = 0; i<128; i++) {
Integer autoBoxed = (int) i;
System.out.println("i:" + i.hashCode() + " autoBoxed:" + autoBoxed.hashCode());
Assert.assertTrue(i == autoBoxed);
}
System.out.println("OK");
// Due to the fact that the JVM has an object pool containing the first 128 (0...127) Integers the code above
// will work but the code below will not.
for (Integer i = 0; i<129; i++) {
Integer autoBoxed = (int) i;
System.out.println("i:" + i.hashCode() + " autoBoxed:" + autoBoxed.hashCode());
Assert.assertTrue("i!=autoboxed", i == autoBoxed);
}
System.out.println("OK");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment