本文介绍了关于自动装箱和对象平等/身份的Java问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Main { 
    /** 
      * @param args the command line arguments */ 
    public static void main(String[] args) { 
        // TODO code application logic here
        int a1 = 1000, a2 = 1000; 
        System.out.println(a1==a2);//=>true 
        Integer b1 = 1000, b2 = 1000;
        System.out.println(b1 == b2);//=>false 
        Integer c1 = 100, c2 = 100; 
        System.out.println(c1 == c2);//=>true 
    }

}

为什么 b1 == b2 false和 c1 == c2 是吗?

Why is b1 == b2 false and c1 == c2 true?

推荐答案

阅读。

Java使用表示整数 s在-128到127之间。

Java uses a pool for Integers in the range from -128 to 127.

这意味着如果你创建一个整数使用整数i = 42; 并且其值介于-128和128之间,创建新对象但返回池中相应的对象。这就是为什么 c1 确实相同 c2

That means if you create an Integer with Integer i = 42; and its value is between -128 and 128, no new object is created but the corresponding one from the pool is returned. That is why c1 is indeed identical to c2.

我假设你知道 == 比较参考,而不是值,当应用于对象时)。

(I assume you know that == compares references, not values, when applied to objects).

这篇关于关于自动装箱和对象平等/身份的Java问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 11:27