For values between the range of -128 to 127 Java points all the Integer/ int references to the same object to save memory.
http://bexhuff.com/2006/11/java-1-5-autoboxing-wackyness
http://stackoverflow.com/questions/1700081/why-does-128-128-return-false-but-127-127-return-true-in-this-code
@Test
public void testExample() {
long l1 = 127;
long l2 = 127;
long l3 = 128;
long l4 = 128;
Integer i1 = 127;
Integer i2 = 127;
Integer i3 = 128;
Integer i4 = 128;
if (l1 == l2) {
System.out.println("l1 == l2");
}
if (l2 == l3) {
System.out.println("l2 == l3");
}
if (l3 == l4) {
System.out.println("l3 == l4");
}
if (i1 == i2) {
System.out.println("i1 == i2");
}
if (i1.equals(i2)) {
System.out.println("i1.equals(i2)");
}
if (i2 == i3) {
System.out.println("i2 == i3");
}
if (i3 == i4) {
System.out.println("i3 == i4");
}
if (i3.equals(i4)) {
System.out.println("i3.equals(i4)");
}
}
No comments:
Post a Comment