您的位置:首页 > 产品设计 > UI/UE

[转载] 在java中为什么变量1000 = 1000 返回false,但是100=100返回true?

2016-10-07 20:19 477 查看
ps:题目的意思是指定义相同内容的不同变量之间的==比较。如果直接比较(100 == 100)的结果是true。

运行以下代码:

Integer a = 1000, b = 1000;
System.out.println(a == b);
Integer c = 100, d = 100;
System.out.println(c == d);


结果是:

false
true


我们知道,如果两个引用指向不同的对象,即使对象拥有相同的内容时,他们用==比较的结果就是不相等(返回false)。

按道理说,最后返回的结果应该也是false才对。但是事实并非如此。

这就是有趣的地方,如果你查看Integer.java类,你会发现Integer类有一个叫做IntegerCache的内部类,这个内部类缓存了所有在-128和127之间的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 -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;
//获取配置中的high值,默认的最大值是127,但是这个值也是可以自定义写在配置文件
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
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);
}
high = h;

cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);//初始化数组的值
}

private IntegerCache() {}
}


所以像以下定义的Integer变量会存在Integer缓存中。

Integer c = 100;//100在-128和127之间。


内部实现是:

Integer i = Integer.valueOf(100);


现在再查看一下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) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
如果值在-128至127的范围之间,它从缓存中返回实际的值。所以

Integer c = 100, d = 100;
实际是指向同一个对象。

这就是当变量c和d比较(==)的结果是true的原因。

System.out.println(c == d);//true
现在你可能会问,为什么这需要缓存呢?

逻辑上的理由是,在这个范围内的“较小”的整数使用远大于较大的,所以使用相同的底层对象是值得的,以减少潜在的内存占用。

以下代码通过反射来获取Integer缓存变量。

public class IntegerDemo {

public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Class cache = Integer.class.getDeclaredClasses()[0]; //1
Field myCache = cache.getDeclaredField("cache"); //2
myCache.setAccessible(true);//3
Integer[] newCache = (Integer[]) myCache.get(cache); //4
for(int i = 0; i < newCache.length; i++){
System.out.printf("index[%d]-->vlaue[%d]\n",i,newCache[i]);
}
}
}


转载自:
作者:林补
链接:https://zhuanlan.zhihu.com/p/20703688
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐