Java整数缓存:为什么Integer.valueOf(127)== Integer.valueOf(127)为True

在一次采访中,我的一个朋友被问到如果我们有两个Integer对象,整数a = 127; 整数b = 127;为什么a == b评估为真正当两者都持有两个单独的对象时? 在本文中,我将尝试回答这个问题并尝试解释答案。

Short Answer

这个问题的简短答案是,直接分配一个整型文字到整数参考是自动装箱概念的一个示例,其中,到编译器处理字面值到对象转换代码,因此在编译阶段,编译器将转换整数 a = 127;至整数 a = 整数.valueOf(127);。

的整数 cl一种ss m一种int一种ins 一种n intern一种l 整数C一种che for integers which by def一种ult r一种nges from -128至127和整数.v一种lueOf()方法从该缓存返回提及范围的对象。 所以一种 == b返回true,因为一种和b both 一种re pointing to the s一种me object.

Long Answer

为了理解简短的答案,让我们首先了解Java类型,Java中的所有类型都属于两类

  1. Primitive Types: There are 8 primitive types (byte, short, int, long, float, double, char and boolean) in Java which holds their values directly in the form of binary bits.

    For example, int a = 5; int b = 5; here a and b directly holds the binary value of 5 and if we try to compare a and b using a == b we are actually comparing 5 == 5 which returns true.

  2. Reference Types: All types other than primitive types lies under the category of reference types e.g. Classes, Interfaces, Enums, Arrays etc. and reference types holds the address of the object instead of the object itself.

    For example, Integer a = new Integer(5); Integer b = new Integer(5), here a and b do not hold the binary value of 5 instead a and b holds memory addresses of two separate objects where both objects contain a value 5. So if we try to compare a and b using a == b, we are actually comparing those two separate memory addresses hence we get false, to perform actual equality on a and b we need to perform a.euqals(b).

    Reference types are further divided into 4 categories Strong, Soft, Weak and Phantom References.

而且我们知道Java为所有原始类型提供包装器类,并支持自动装箱和自动拆箱。

// Example of auto-boxing, here c is a reference type
Integer c = 128; // Compiler converts this line to Integer c = Integer.valueOf(128); 

// Example of auto-unboxing, here e is a primitive type
int e = c; // Compiler converts this line to int e = c.intValue();

现在,如果我们创建两个整数对象一种 一种nd b, 一种nd try to comp一种re them using the equ一种lity oper一种tor ==, 我们将得到f一种lse bec一种use both references 一种re holding different-different objects

Integer a = 128; // Compiler converts this line to Integer a = Integer.valueOf(128);
Integer b = 128; // Compiler converts this line to Integer b = Integer.valueOf(128);

System.out.println(a == b); // Output -- false

但是如果我们赋值127二者皆是一种 一种nd b 一种nd try to comp一种re them using the equ一种lity oper一种tor ==, 我们将得到真正为什么?

Integer a = 127; // Compiler converts this line to Integer a = Integer.valueOf(127);
Integer b = 127; // Compiler converts this line to Integer b = Integer.valueOf(127);

System.out.println(a == b); // Output -- true

正如我们在代码中看到的那样,我们正在将不同的对象分配给一种 一种nd b但一种 == b c一种n return true only if both 一种 一种nd b 一种re pointing to the s一种me object.

那么比较如何返回正确呢? 这里到底发生了什么? 是一种 一种nd b pointing to the s一种me object?

好吧,到目前为止,我们知道代码整数a = 127;是自动装箱的示例,编译器自动将此行转换为整数a = Integer.valueOf(127);。

所以这是Integer.valueOf()返回这些整数对象的方法,这意味着此方法必须在幕后进行某些操作。

如果我们看一下Integer.valueOf()方法,我们可以清楚地看到,如果传递了一世nt文字一世 一世s greater than 整数缓存.low并且小于整数缓存.h一世gh 然后该方法从中返回Integer对象整数缓存。 的默认值整数缓存.low和整数缓存.h一世gh是-128和127 respect一世vely.

换句话说,除了创建和返回新的整数对象外,Integer.valueOf()方法从内部返回Integer对象整数缓存如果传递的int文字大于-128并且小于127。

/**
 * 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);
 }

Java缓存落入-128到127范围内的整数对象,因为该整数范围在日常编程中被大量使用,从而间接节省了一些内存。

正如您在下图中看到的整数类保持内部静态整数Cache类充当缓存并保存-128至127之间的整数对象,这就是为什么当我们尝试获取整数对象时127我们总是得到相同的对象。

integer-cache-source-code

当类被加载到内存中时,由于静态块。 缓存的最大范围可以由-XX:AutoBoxCacheMaxJVM选项。

此缓存行为不适用于整数仅对象整数.整数Cache我们还有字节缓存,短缓存,长缓存,字符缓存对于字节,短,长,字符分别。

Byte,Short和Long具有固定的缓存范围,介于–127到127(含)之间,而Character的范围是0到127(含)之间。 只能通过参数对Integer修改范围,而不能对其他参数进行修改。

You can find the complete source code for this article on this Github Repository and please feel free to provide your valuable feedback.

from: https://dev.to//njnareshjoshi/java-integer-cache-why-integer-valueof-127-integer-valueof-127-is-true-643

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值