【神奇现象】java整型数的神奇内部缓存类
程序员文章站
2022-06-01 20:24:09
...
一、常量与对象的比较
这样的代码结果会是什么?
int a = 1000,b=1000;
System.out.println(a == b);//1
Integer c = 1000, d = 1000;
System.out.println(c == d);//2
结果是:
true
false
知识点:大家都知道这其实是一个常量比较,一个是对象之间比较。根本是比较的指向地址.
然而把上述的数字改为100,结果还会这样吗
int a = 100,b=100;
System.out.println(a == b);//1
Integer c = 100, d = 100;
System.out.println(c == d);//2
结果是:
true
true
这里是不是出现了神奇之处了呢(有趣~~哈哈哈)
原因就是,查看Integer源码会发现有一个内部缓存类IntegerCache ,它缓存了一定范围的数(Integer127 ~ -128会存在一个缓存里)
下面代码来自Integer类里
/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/
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() {}
}
还有一段valueof方法
/**
* 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);
}
所以事情就成了,所有的小整数在内部缓存,然后当我们声明类似——
Integer c = 100;
的时候,它实际上在内部做的是
Integer i = Integer.valueOf(100);
类似的Long、Bety 里面都有类似的缓存类。
以上都是自己见解,如有误,请大家多多指教
参考 :https://blog.csdn.net/xlgen157387/article/details/51261859
上一篇: CSS伪类选择器,引入字体图标,盒模型以及em和rem的区别
下一篇: java —— 神奇的幻方