- 引言
学习java的最好方法就是看源码和官方文档
关于Integer的缓冲池IntegerCache这里从源码角度进行分析,但是Integer的缓冲池与jvm内存模型之间的关系还有待研究。
- Integer类源码分析
jdk版本:jdk1.8
public final class Integer extends Number implements Comparable<Integer> {
/*
* 内部静态类
*/
private static class IntegerCache {
//声明缓存池下界
static final int low = -128;
//声明缓存池上界
static final int high;
//声明缓存数组
static final Integer cache[];
//静态块
static {
//缓存池的上界默认为127,可以自己设置
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;
//初始化缓存池的大小为256
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
//将值存储到缓冲池中
cache[k] = new Integer(j++);
/*
此处使用断言,用于保证程序的安全
如果表达式值为true,则继续执行,如果表达式的值为false则中止程序
*/
assert IntegerCache.high >= 127;
}
//构造方法
private IntegerCache() {}
}
//返回一个整数实例
//如果此值在-127和128之间则在缓冲池中获取,否则进行创建新的对象
public static Integer valueOf(int i) {
//如果i值在缓冲池范围内,则返回缓冲池cache中的i值,如果不在范围内则直接创建新对象
if (i >= IntegerCache.low && i <= IntegerCache.high)
//缓冲池的值为-128到127之间
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
//声明final类型的参数
private final int value;
//构造方法,参数为int类型
public Integer(int value) {
this.value = value;
}
/*
重写equals方法,此方法判断的是int值得大小
*/
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
}
实例1:
public class Main {
public static void main(String[] args) {
//直接赋值-缓冲池范围内
Integer integer1 = 127;
Integer integer2 = 127;
System.out.println(integer1 == integer2);
System.out.println(integer1.equals(integer2));
}
}
结果为true,true
解析:在Integer的缓冲池范围内进行赋值时直接从缓冲池中获取,==判断的是值;Integer的equals方法根据value值进行判断
实例2:
public class Main {
public static void main(String[] args) {
//直接赋值-缓冲池范围外
Integer integer3 = 400;
Integer integer4 = 400;
System.out.println(integer3 == integer4);
System.out.println(integer4.equals(integer4));
}
}
结果为false,true
解析:Integer赋值如果在缓冲池外时则直接创建对象,==判断的是对象的引用值;Integer的equals方法根据value值进行判断
实例3:
public class Main {
public static void main(String[] args) {
Integer integer5 = new Integer(500);
Integer integer6 = new Integer(500);
System.out.println(integer5 == integer6);
System.out.println(integer5.equals(integer6));
}
}
结果为false,true
解析:此时为Integer创建对象,==判断是对象的引用值;equals()方法判断的是Integer的value值
实例4:
public class Main {
public static void main(String[] args) {
System.out.println(Integer.valueOf(127) == Integer.valueOf(127));
System.out.println(Integer.valueOf(128) == Integer.valueOf(128));
}
}
结果为true,false
解析:valueOf()方法返回的是Integer类型的实例,它在创建对象的时候底层对i值进行了判断,如果i值在缓冲池范围内则直接缓冲池中获取,否则创建对象。
- 扩展
Integer缓冲池的上界可以进行设置,方法还有待研究;
Integer是一个final修饰的不变类,基础了Number抽象类
IntegerCache是Integer内部的私有静态类