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. final评价Ⅱ

    1.飞天小女警: 礼物挑选这个项目相比之前的发布功能更完善了些,但是整体界面还是不太美观,用户界面上呈现出的选项字不够清晰,使用起来不是很方便,但是增加了猜你喜欢的功能,可以根据用户的浏览记录猜测用户 ...

  2. C语言字符串操作总结大全(超详细)

    本篇文章是对C语言字符串操作进行了详细的总结分析,需要的朋友参考下 1)字符串操作  strcpy(p, p1) 复制字符串  strncpy(p, p1, n) 复制指定长度字符串  strcat( ...

  3. (转) Awesome Deep Learning

    Awesome Deep Learning  Table of Contents Free Online Books Courses Videos and Lectures Papers Tutori ...

  4. polyfill之javascript函数的兼容写法——Array篇

    1. Array.isArray(obj) if (!Array.isArray) { Array.isArray = function(arg) { return Object.prototype. ...

  5. dw的流体网格布局

    在设计视图拖拽 在插入面板中选择插入流体网格布局标签 在对话框中如果不选中新建行复选框 如果总的列数是5列 一行的列宽和上一行的列宽加起来没有5列的话,下一行会上浮

  6. div模态层示例

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  7. int.Parse()、int.TryParse()和Convert.ToInt32()的区别

    1:int.Parse(一个参数)        此参数必须满足: 1 只能是字符串: 2 只能是 “整型” 字符串,即各种整型ToString()之后的形式,也不能为浮点型. 2:int.TryPa ...

  8. Object类的toString方法

          Object类是所有Java类的祖先.每个类都使用 Object 作为超类.所有对象(包括数组)都实现这个类的方法.在不明确给出超类的情况下,Java会自动把Object作为要定义类的超类 ...

  9. 使用Spring缓存的简单Demo

    使用Spring缓存的简单Demo 1. 首先创建Maven工程,在Pom中配置 <dependency> <groupId>org.springframework</g ...

  10. C++程序设计(关于函数中数组传递的一点心得)

    题目: 10个学生考完期末考试评卷完成后,老师需要划出及格线,要求如下: (1) 及格线是10的倍数: (2) 保证至少有60%的学生及格: (3) 如果所有的学生都高于60分,则及格线为60分:   ...