编程语言
首页 > 编程语言> > Java 有关 Integer 一个好玩的包装类

Java 有关 Integer 一个好玩的包装类

作者:互联网

废话不多说,看看下面的代码。

        Integer i1 = 100;
        Integer i2 = 100;
        Integer i3 = 200;
        Integer i4 = 200;

        System.out.println(i1 == i2);
        System.out.println(i3 == i4);

你可以猜猜上面的代码输出的是什么吗?

解答

上面代码输出的是 ture 和 false

首先需要知道,Java 在对象中使用 == 比较的是地址,不是值。

因为我们使用类包装类,那么有关 int 的包装类肯定在这里有一个诡异的地方,这个诡异的地方就在于:

在通过 valueOf 方法创建 Integer 对象的时候,如果数值在 [-128,127] 之间,便返回指向IntegerCache.cache中已经存在的对象的引用;否则创建一个新的Integer对象。

 

integer-w-c-01

 

下面的代码就是 Int 的有关 valueOf

 

integer-w-c-02

 

关于英文的说明就是:

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.

为了更好的空间和时间性能,对在 -128 到 127 之间的整数进行缓存了,对这个这个区间之外的变量也有可能进行了缓存。

因此上面的代码就会得到上面的结果。

有相同情况的还包括有 Long,我们看了下 Double 和 Float 这 2 个对象,Java 并没有对这 2 个对象进行缓存。

https://www.ossez.com/t/java-integer/13782

标签:Java,代码,cache,127,128,Integer,好玩
来源: https://www.cnblogs.com/huyuchengus/p/15473764.html