Java自动装箱与拆箱

1.什么叫自动装箱和拆箱?
装箱:原始类型转换为对应的对象。
拆箱:对象转换为原始类型。

2.什么时候会进行装箱和拆箱?
(1)赋值的时候

  Integer i = 100;//box重点内容-->Integer i = Integer.valueOf(100);
  int t = i; //unbox-->int t = i.intValue();   

(2)运算的时候

  int i2 = 100;
  System.out.println(i2 == i); //true

输出结果为true,证明是i进行了拆箱,因为如果i2进行了装箱的话,就新建了一个对象,结果就会是false了。
(3)方法调用的时候

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1); //-->box

3.自动装箱的利弊
(1)弊端-影响性能
在循环里面做运算的时候,要特别注意自动装箱的问题,不然会创建出多余的对象,影响性能。

    Integer sum = 0;
    for(int i = 1000;i<5000;i++){
        sum +=i;
    }

上面的sum +=i,首先sum进行自动拆箱,然后进行运算,最后再发生自动装箱。内部变化如下:

    sum = sum.intValue() +i;
    Integer sum = new Integer(result);

上面由于将sum定义为Integer,将会产生将近4000个无用的Intege对象,大大的降低了程序的性能并加重了垃圾回收的工作量。因此我们在编程中,要正确地声明变量类型,避免因为自动装箱引起的性能问题。在这里就可以将sum定义为int型,即可解决问题。
(2)利端-可以使代码变得简洁。

4.其他
(1)对象进行值比较时,使用equals方法,但要判断空指针异常。
(2)在Java中,会对-128到127的Integer对象进行缓存,当创建新的Integer对象时,如果符合这个这个范围,并且已有存在的相同值的对象,则返回这个对象,否则创建新的Integer对象。

另附对象比较的各种情况代码:

public class AutoBoxingAndUnBoxingTest {

    public static void main(String[] args) {
        //Integer example
        //what are the box-actions?
        Integer i = 100; //autobox-->Integer i = Integer.valueOf(100);
        int t = i; //unbox-->int t = i.intValue();

        //not in (-128,127)
        Integer i1 = 200;
        Integer i2 = 200;
        System.out.println(i1 == i2);    //false two different object
        System.out.println(i1.equals(i2)); // true 

        //in(-128,127)
        Integer i3 = 100;
        Integer i4 = 100;
        System.out.println(i3 == i4); //i3 and i4 point to the same object

        //int and Integer
        int i5 = 100;
        Integer i6 = 100;
        System.out.println("i5==i6:"+(i5 == i6)); // i6 unbox
        System.out.println(i6.equals(i5)); // i5 box

        //Integer and Integer 
        Integer i7 = new Integer(100);
        Integer i8 = new Integer(100);
        System.out.println(i7 == i8); //false
        System.out.println(i7.equals(i8)); //true

        //String example
        String s1 = "a";
        String s2 = "a";
        System.out.println(s1 == s2); //true
        System.out.println(s1.equals(s2)); //true

        String s3 = new String("a");
        String s4 = new String("a");
        System.out.println(s3 == s4); //false
        System.out.println(s3.equals(s4)); //true

        String d = "2";
        String e = "23";
        e = e.substring(0,1);
        System.out.println(e.equals(d)); //true
        System.out.println(e == d); //false

    }
}

参考:
http://blog.csdn.net/jairuschan/article/details/7513045
http://www.cnblogs.com/danne823/archive/2011/04/22/2025332.html
http://www.importnew.com/15712.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值