标签:Java int cache equals IntegerCache 整型 127 128 Integer
Java开发手册说明:
对于 Integer var = ? 在-128 至 127 之间的赋值,Integer 对象是在 IntegerCache.cache 产生,会复用已有对象,这个区间内的 Integer 值可以直接使用==进行判断,但是这个区间之外的所有数据,都会在堆上产生,并不会复用已有对象,这是一个大坑,推荐使用 equals 方法进行判断。
问题分析
@Test
public void testInteger(){
Integer var1 = 100;
Integer var2 = 100;
System.out.println(var1==var2);//true
Integer var3 = 128;
Integer var4 = 128;
System.out.println(var3==var4);//false
Integer var5 = new Integer(100);
Integer var6 = new Integer(100);
System.out.println(var5==var6);//false
}
发现var1和var2是同一对象,而var3和var4不是同一对象,var5和var6是不同的对象,这是什么原因呢?我们看一下源码。
在基本类型转为包装类的时候会调用valueOf(int i)
方法。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
在valueOf方法中,会先将及基本类型的值与IntegerCache
的最大最小值比较,如果在其中的话,就返回cache
数组中的对象。如果不在其中,就通过Integer的构造方法创建对象。
IntegerCache
是Integer
的内部类,默认初始化了一个值在[-128,127]的Integer数组cache
。
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() {}
}
所以如果值在[-128,127]之间,会直接从IntegerCache
取值。其中IntegerCache
的最大值可以通过JVM的初始化参数来调节。
-Djava.lang.Integer.IntegerCache.high=1024
如果直接通过Integer的构造方法来创建对象,则会绕过IntegerCache
。
private final int value;
public Integer(int value) {
this.value = value;
}
开发手册中指出:所有整型包装类对象之间值的比较,全部使用 equals 方法比较。
标签:Java,int,cache,equals,IntegerCache,整型,127,128,Integer 来源: https://www.cnblogs.com/zjw-blog/p/13943412.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。