The integer class in the Java.lang package is one of our more common classes, such as the following code:
Integer a=new integer (1)
Integer a=integer.valueof (1);
All two get an integer object, but the integer.valueof is highly efficient. Why, then? Because integer.valueof used the caching mechanism.
Where the Integer.valueof method code is as follows:
public static Integer valueof (int i) {
Final int offset = 128;
if (i >= -128 && i <= 127) {//must cache
return integercache.cache[i + offset];
}
return new Integer (i);
}
A helper class Integercache is used in this class, where the source code for Integercache is as follows:
private Static Class Integercache {
Private Integercache () {}
Static final Integer cache[] = new integer[-(-128) + 127 + 1];
static {
for (int i = 0; i < cache.length; i++)
Cache[i] = new Integer (i-128);
}
}
You can see that the cache array has been initialized in Integercache. So, note that the new integer returns a different object forever, but when the integer range is -128<i<=127, INTEGER.VALUEOF returns the same object.
Look at the following code:
Integer a=new integer (1);
Integer b=new integer (1);
Integers range from 128 to 127 and return the same object
Integer c=integer.valueof (1);
Integer d=integer.valueof (1);
Not the same object returned
Integer e=integer.valueof (200);
Integer f=integer.valueof (200);
System.out.println (A==B);
System.out.println (C==d);
System.out.println (E==F);
The results of the program running are:
False
True
False