java中不一致的拆箱技术

时间:2015-07-22 10:53:30

标签: java autoboxing

代码下方

package AutoBoxing;

/*
 * When a wrapper type is initialized do you get a new object created?
 * Answer: It depends!!!!
 * 1) If you use a constructor then a new instance will be created.
 * 2) If you use boxing('Integer i = 127'), and the value being boxed is a 
 * boolean, byte, char in the range \u0000 to \u007f, int or short in the 
 * range -128 to 127 then there is a single object. Technical phrase is 'interned'  
 */
public class Example2 {

    public static void main(String[] args) {
        Integer i = 127, j = 127;
        Integer k = new Integer(127);
        System.out.println(i == j); // unboxed values are compared
        System.out.println(i == k); // memory addresses are compared

    }

}

给出

true
false

作为输出。

true因为对象已取消装箱并且比较了值(127 == 127)。

false因为比较了内存​​地址。

为什么在第二种情况下没有进行拆箱?因为k也是原始类型的包装类?

0 个答案:

没有答案