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]; //
Field myCache = cache.getDeclaredField("cache"); //
myCache.setAccessible(true);//
Integer[] newCache = (Integer[]) myCache.get(cache); //
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
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

[转载] 在java中为什么变量1000 = 1000 返回false,但是100=100返回true?的更多相关文章

  1. 转载:java中Thread.sleep()函数使用

    点我跳过黑哥的卑鄙广告行为,进入正文. Java多线程系列更新中~ 正式篇: Java多线程(一) 什么是线程 Java多线程(二)关于多线程的CPU密集型和IO密集型这件事 Java多线程(三)如何 ...

  2. java中打印变量地址

    在java中打印变量的地址 这个代码是在startoverflow上看到的,跟大家分享一下. import sun.misc.Unsafe; import java.lang.reflect.Fiel ...

  3. Java中的变量与变量的作用域

    关于Java中的变量及变量的作用域 关于Java中的变量及变量的作用域 0. 变量的概念 在程序运行期间,系统可以为程序分配一块内存单元,用来存储各种类型的数据.系统分配的内存单元要使用一个标记符来标 ...

  4. Java中静态变量与实例变量

    知识回顾 上一篇总结了java中成员变量和局部变量的区别,这一篇将总结静态变量和实例变量的一些特性和区别. 示例代码 package Variable; public class VariableDe ...

  5. Java中关于变量的几种情况

    Java中关于变量的几种情况 1.继承时变量的引用关系 class Animals { int age = 10; void enjoy() { System.out.println("An ...

  6. Java中静态变量的声明位置

    Java中静态变量只能是成员变量,局部方法中的局部变量除final外不能有任何其他修饰符,例如: public class Test { static String x = "1" ...

  7. 【转载】Java中String类的方法及说明

    转载自:http://www.cnblogs.com/YSO1983/archive/2009/12/07/1618564.html String : 字符串类型 一.      String sc_ ...

  8. 004 java中的变量

    这篇文章为你搞懂三个问题 什么是变量? 如何使用变量? 变量命名有哪些规范? 变量 计算机的内存类似于人的大脑,电脑使用内存来存储计算所需要的数据. 内存像旅馆一样,不同的房间类型对应不同的数据类型, ...

  9. java中static变量和方法的总结

    转自:http://blog.csdn.net/haobo920/article/details/5921621 java中static变量和方法的总结 java中一切皆是对象 一个类中对象的定义一般 ...

随机推荐

  1. CE创建进程和线程

    创建进程: HWND hWnd = NULL; PROCESS_INFORMATION pi = {}; if(NULL==hWnd) { hWnd=FindWindow(NULL,_T(" ...

  2. Servlet页面注册用户的小程序(一)

    本实例实现用userreg.jsp页面中的表单提交注册请求,把注册信息提交给regservlet写入数据库并且查询新用户显示出来. 一.准备工作. 1.jdbc数据驱动开发包mysql-connect ...

  3. MongoDB学习笔记六:进阶指南

    [数据库命令]『命令的工作原理』MongoDB中的命令其实是作为一种特殊类型的查询来实现的,这些查询针对$cmd集合来执行.runCommand仅仅是接受命令文档,执行等价查询,因此,> db. ...

  4. CefBrowser 复制图片解决办法

    使用的是CefSharp控件,开放出的功能比较多,但是还是有一些封闭的.例如复制图片到Clipbord,库没有提供. VC虽然看得懂,但托管代码没搞过,看得很蛋痛,而且如果有CefSharp有新版本还 ...

  5. 中介者模式(Mediator Pattern)

    定义一个中介对象来封装系列对象之间的交互.中介者使各个对象不需要显示地相互引用,从而使其耦合性松散,而且可以独立地改变他们之间的交互. Mediator:中介者接口.在里面定义了各个同事之间相互交互所 ...

  6. webpack es6 to es5支持配置

    1. 安装webpack npm install webpack --save-dev 2. 安装babel  实现 ES6 到 ES5 npm install --save-dev babel-co ...

  7. MSI Error 1603 installing AppFabric 1.1 / Win7 x64

    MSI Error 1603 installing AppFabric 1.1 / Win7 x64  Archived Forums A-B > AppFabric Caching   先说解 ...

  8. windows下安装boost库

    工作中现在会接触boost,所以我计划两个月之内努力熟悉一下boost.今天在自己win10系统上尝试安装了boost库,下面把遇到的问题总结一下: 1. 下好1.61版本库,在boost目录下运行b ...

  9. Play with docker 1.12

    Docker v1.12 brings in its integrated orchestration into docker engine. Starting with Docker 1.12, w ...

  10. 解决“动软代码生成器在SqlServer中会将唯一索引识别为主键"的Bug

    动软代码生成器在SqlServer中,生成的代码会将唯一索引错误地识别为主键, 反编译源代码后,发现其中的SQL条件有误,现修复此Bug. 修复方法:将附件中的”Maticsoft.DbObjects ...