整数对象缓存

Integer object caching

我读到 "So when creating an object using Integer.valueOf or directly assigning a value to an Integer within the range of -128 to 127 the same object will be returned."

这就是为什么:-

Integer a=100;
Integer b=100;
if(a==b) // return true as both the objects are equal

但为什么不在下面这个案例中呢? 这两个值也在 127 和 -128 范围内,因此根据上面的陈述,这两个值也将 return 相同的对象。

但是这里的输出是 "Not"

public static void main(String[] args) {

    Integer a = 10;
    Integer b = 12;
    if(a == b)
        System.out.println("same");
    else
        System.out.println("Not");
}

谁能解释一下?

== 检查两个引用是否指向 相同的内存位置。
在第一种情况下 两个值相同 所以它们指向相同的位置只有 一个对象 将被创建。

Integer a=100;
Integer b=100;
if(a==b) // return true as both the objects are equal


在第二种情况下,两个值不同,因此它们各自具有不同的内存位置,因此将创建 两个对象

public static void main(String[] args) {

    Integer a = 10;
    Integer b = 12;
    if(a == b)
        System.out.println("same");
    else
        System.out.println("Not");
}

如果您阅读实际内容 Java doc,您会更清楚地了解它实际在做什么

Returns an Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor 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.

由于返回的 Integer 必须代表指定的 int 值,所以

不可能
Integer a = 10;
Integer b = 12;
System.out.println((a==b));

将打印 "true",因为同一个对象显然不能表示两个值。

编辑:

为了精确起见 - Java 标准不要求整数自动装箱(将原语 int 分配给 Integer 对象)使用 Integer.valueOf(),所以很有可能在符合 Java 的实现中

Integer a = 10;
Integer b = 10;
System.out.println((a==b));

将打印 "false";

您误解了 "the same object will be returned" 的意思。

因此,与==的比较实际上是比较内存位置,而returns仅当两个变量持有相同的对象(即存储在相同的内存位置)时才为真。

整数常量池中存储的是-128到127之间的值,也就是说每10都是10(即同一个内存位置),每12都是12,等等。但是不是所有10也是12的情况,这是你的问题无意中假设的。

无论如何,一旦超出该范围,每个原始 int 都是一个新对象,并被分配到常量池之外的新内存位置。

您可以使用以下代码进行测试:

public static void main(String[] args) {

    Integer a = 1000;
    Integer b = 1000;
    if(a == b)
        System.out.println("same");
    else
        System.out.println("Not");
}

这将打印 "Not",因为 ab 是存储在不同内存位置的两个不同对象。

这就是为什么您应该将事物与 .equals()

进行比较

简单地说,它们不是同一个对象,它们是两个不同的 Integer 实例,用于保存给定的值,所以就好像对象不同一样,它总是打印 Not