int、Interger的值为什么有时候相等,有时候不相等?

提前需知:

1.Integer有一个常量池,存放着-128~127之间的数值,在这里的数值在用的时候会从这个缓存中取;

2.new Integer(10)类似的不管常量池里面有没有都会从堆中分配一个内存;

3. Integer和int运算的时候会自动拆箱(将Integer拆成int);

4.==号比较的是内存地址;

5.equals比较值;

public static void main(String[] args) {
        System.out.println("**********在-128~127区间***************");
        Integer a = 1;
        Integer a1 = 1;
        int b = 1;
        int b1 = 1;
        Integer c = new Integer(1);
        System.out.println((a == a1) + " : " + (a.equals(a1)));
        System.out.println(b == b1);
        System.out.println((a == b) + " : " + (a.equals(b)));
        System.out.println((b == c) + " : " + (a.equals(c)));// ==号为true 因为自动拆箱成int
        System.out.println((a == c) + " : " + (a.equals(c)));//==号为false 两个对象地址不相同,a在IntegerCache.cache中(缓存策略只在自动装箱的时候有用),b在堆中,所以两者地址不相同
        System.out.println(a.equals(b));
        
        System.out.println("**********超出-128~127区间***************");
        Integer aa = 1111;
        Integer aa1 = 1111;
        int bb = 1111;
        int bb1 = 1111;
        Integer cc = new Integer(1111);
        System.out.println((aa == aa1) + " : " + (aa.equals(aa1)));//超出范围则不在Integer缓存中复用,而是直接在堆中产生
        System.out.println(bb == bb1);
        System.out.println((aa == bb) + " : " + (aa.equals(bb)));
        System.out.println((bb == cc) + " : " + (aa.equals(cc)));
        System.out.println((aa == cc) + " : " + (aa.equals(cc)));
    }
运行结果:

**********在-128~127区间***************
true : true
true
true : true
true : true
false : true
true
**********超出-128~127区间***************
false : true
true
true : true
true : true
false : true
结果解析:

1.在-128~127之间的数存放在常量池中,所以a == a1是为true(内存地址相同),超出范围的将会直接从堆中分配一个新的空间来存储,所以bb == bb1(内存地址不相同);  //查看提前需知1和4

2. a == c 的结果是false是因为c是从堆中从新分配了内存,所以和常量池中的a不想等;//查看提前需知2和4

3.aa ==cc的结果是false是因为两者都是在堆中分配了不同的内存//查看提前须知1和2

4.aa == bb和a == b都是true;//查看提前须知3

5.所有的equals输出都是true;//查看提前须知5




猜你喜欢

转载自blog.csdn.net/tab_yls/article/details/79017425