目录
写在开头
自动装箱和拆箱、for循环都是java语言的语法糖!!
《深入理解JVM虚拟机》
Integer包装类的缓存机制
Integer的缓存机制: Integer是对小数据(-128~127)是有缓存的,再jvm初始化的时候,数据-128~127之间的数字便被缓存到了本地内存中,如果初始化-128~127之间的数字,会直接从内存中取出,不需要新建一个对象。
这种 Integer 缓存策略仅在自动装箱(autoboxing)的时候有用,使用构造器创建的 Integer 对象不能被缓存。
IntegerCache,Javadoc 详细的说明这个类是用来实现缓存支持,并支持 -128 到 127 之间的自动装箱过程。最大值 127 可以通过 JVM 的启动参数 -XX:AutoBoxCacheMax=size 修改。
缓存通过一个 for 循环实现。从小到大的创建尽可能多的整数并存储在一个名为 cache 的整数数组中。这个缓存会在 Integer 类第一次被使用的时候被初始化出来。以后,就可以使用缓存中包含的实例对象,而不是创建一个新的实例(在自动装箱的情况下)。
缓存机制,本质上通过静态内部类,实现懒加载,for循环设置内部类的数组范围。
Integer源码(节选)
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
//静态内部类
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
其他包装类的缓存行为
这种缓存行为不仅适用于Integer对象。我们针对所有整数类型的类都有类似的缓存机制。
有 CharacterCache 用于缓存 Character 对象,缓存范围是[0,127]
有 ByteCache 用于缓存 Byte 对象,缓存范围是[-128,127]
有 ShortCache 用于缓存 Short 对象,缓存范围是[-128,127]
有 LongCache 用于缓存 Long 对象,缓存范围是[-128,127]
除了 Integer 可以通过参数改变范围外,其它的都不行。修改虚拟机的Integer缓存最大值。
自动装箱
java的语法糖之一,8种基本类型对应8种包装类。Java 编译器把原始类型自动转换为封装类的过程称为自动装箱(autoboxing),这相当于调用 valueOf 方法。
基本数据类型
包装类
byte
Byte
short
Short
int
Integer
long
Long
char
Character
float
Float
double
Double
boolean
Boolean
Integer初始化的三种方式
Integer a = 10; //this is autoboxing,自动装箱,等价于Integer.valueOf()
Integer b = Integer.valueOf(10); //under the hood,使用缓存机制
Integer num1 = new Integer(100);//创建新的操作对象
比较运算符的应用
==:java中的==是用于判断两个操作数是否相等的,如果操作数是基本数据类型,则判断值是否相等;如果操作数是对象,则判断两个对象的地址是否相等(也就是引用是否相等),所以,这里就很明确了,num1 和num2是两个对象,自然地址是不一样的。
equals:值比较同数据类型的两个对象的数据值。
参考文章: