My colleague sent me today a PPT about the Java disassembly box, which has a piece of code
Integer C = integer.valueof (3= integer.valueof (3= integer.valueof (321= integer.valueof ( 321= =
The output is, but why?
true false
Let's take a look at the source of the integer
Public Static Integer valueOf (int i) { if (i >= integercache.low && i <= integercache . High) return integercache.cache[i + (-integercache.low)]; return New Integer (i); }
Code for inner class Integercache
Private Static classIntegercache {Static Final intLow =-128; Static Final intHigh ; Static FinalInteger cache[]; Static { //High value is configured by property intH = 127; String Integercachehighpropvalue=Sun.misc.VM.getSavedProperty ("Java.lang.Integer.IntegerCache.high"); if(Integercachehighpropvalue! =NULL) { Try { inti =parseint (Integercachehighpropvalue); I= Math.max (i, 127); //Maximum array size is Integer.max_valueh = math.min (i, Integer.max_value-(-low)-1); } Catch(NumberFormatException nfe) {//If The property cannot is parsed into an int, ignore it.}} High=h; Cache=Newinteger[(high-low) + 1]; intj =Low ; for(intk = 0; K < Cache.length; k++) Cache[k]=NewInteger (j + +); //range [ -128, 127] must be interned (JLS7 5.1.7) assertIntegercache.high >= 127; } PrivateIntegercache () {}}
As you can see, the number between [-128, 127] is cached and is the same object. Outside of this range is not the same object, so E==f is False
Integercache Small in Java integer