int
int是java的八个原始数据类型之一,java的原始数据类型有(boolean,byte,short,chat,int,float,double,long)
虽说java的万物皆对象,但原始数据类型是例外。
Integer
Integer是int的包装类,提供一些转换(如:Integer.parseInt())之类的操作。
在使用泛型时,不能直接使用int,如List,需要使用List
在java5提供了自动装箱和拆箱的功能。
自动装箱,拆箱
所谓自动装箱指的是java在程序编译时,会自动的进行转换,如int转Integer,最终生成的字节码跟都用一种类型生成的字节码是一致的。
一般在使用时不需要刻意的在乎装箱行为,但是最好是避免装箱和拆箱行为。
例如在性能很重要的场景,如果int都转为Integer,就会导致创建了很多的java对象,这对内存占用是有一定影响的。
Integer使用valueOf方法将int自动转为Integer对象。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
Integer使用intValue自动转为int原始类型:
//Integer源码
/**
* The value of the {@code Integer}.
* @serial
*/
private final int value;
public int intValue() {
return value;
}
Integer 值缓存
int类型的值最常用的范围在[-128,127]之间,因此在最开始时,Integer类中的静态类对象IntegerCache就会被加载到内存中,其类内有 Integer cache[]数组,保存-128到127的Integer对象。
值缓存是值在创建Integer对象时,会看这个int值大小是否在IntegerCache的范围内(默认时[-128,127],如果有自定义该cache范围参数且大于127时,则以自定的为准)
如果大小在[-128,127]则,直接使用cache内的Integer对象,不需要再创建对象。
如果大小不在该范围内,则会创建Integer对象。
源码实现如下:
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() {}
}