java - Why does 128==128 return false but 127==127 return true when converting to Integer wrappers? -
class d { public static void main(string args[]) { integer b2=128; integer b3=128; system.out.println(b2==b3); } }
output:
false
class d { public static void main(string args[]) { integer b2=127; integer b3=127; system.out.println(b2==b3); } }
output:
true
note: numbers between -128 , 127 true.
when compile number literal in java , assign integer (capital i
) compiler emits:
integer b2 =integer.valueof(127)
this line of code generated when use autoboxing.
valueof
implemented such numbers "pooled", , returns same instance values smaller 128.
from java 1.6 source code, line 621:
public static integer valueof(int i) { if(i >= -128 && <= integercache.high) return integercache.cache[i + 128]; else return new integer(i); }
the value of high
can configured value, system property.
-djava.lang.integer.integercache.high=999
if run program system property, output true!
the obvious conclusion: never rely on 2 references being identical, compare them .equals()
method.
so b2.equals(b3)
print true logically equal values of b2,b3.
note integer cache not there performance reasons, rather comform jls, section 5.1.7; object identity must given values -128 127 inclusive.
integer#valueof(int) documents behavior:
this method yield better space , time performance caching requested values. method cache values in range -128 127, inclusive, , may cache other values outside of range.
Comments
Post a Comment