JAVA知识捡漏——拆箱和装箱

1.什么是装箱和拆箱

自动根据数值创建对应的Integer对象,这就是装箱。
自动将包装器类型转换为基本数据类型,这就是拆箱。

2.装箱和拆箱是如何实现的

java1.5开始的自动装箱拆箱机制其实是编译时自动完成替换的,装箱阶段替换为valueOf方法,拆箱阶段自动替换xxxValue方法。
对于Integer、Short、Byte、Character、Long类型的valueOf方法,参数如果在-128~127之间的值会直接返回内部缓冲池中已经存在对象的引用,参数是其他范围的值则返回新建对象。
对于Double、Float类型与Integer类型类似,一样会调用Double、Float的ValueOf方法,但是不管传入的参数值是多少都会new一个对象来表达该数值,因为在某个范围内的整型数值的个数是有限的,而浮点数却不是。

3.java拆箱装箱实例
        Integer i1=100;
		Integer i2=100;
		Integer i3=200;
		Integer i4=200;
		
		System.out.println(i1==i2); //true
		System.out.println(i1.equals(i2)); //true
		System.out.println(i3==i4);  //false
		System.out.println(i3.equals(i4));  //true
		
		Double d1=100.0;
		Double d2=100.0;
		Double d3=200.0;
		Double d4=200.0;
		System.out.println(d1==d2);  //false
		System.out.println(d1.equals(d2));  //true
		System.out.println(d3==d4);  //false
		System.out.println(d3.equals(d4));  //true

        Boolean b1=false;
		Boolean b2=false;
		Boolean b3=true;
		Boolean b4=true;
		System.out.println(b1==b2);  //true
		System.out.println(b3==b4);  //true

对于两边都是包装类型的比较**==比较的是引用,equals比较的是值。**

        Integer a=1;
		Integer b=2;
		Integer c=3;
		Integer d=3;
		Integer e=321;
		Integer f=321;
		
		Long g=3L;
		Long h=2L;
		
		System.out.println(c==d);  //true
		System.out.println(e==f);  //false
		System.out.println(c==(a+b)); //true
		System.out.println(c.equals(a+b)); //true
		System.out.println(g==(a+b)); //true
		System.out.println(g.equals(a+b));  //false
		System.out.println(g.equals(a+h));  //true

        Integer m=444;
		int n=444;
		System.out.println(m==n);  //true
		System.out.println(m.equals(n));  //true

对于两边有一边是表达式(包含算式运算)则==比较的是数值(自动触发拆箱过程),对于包装类型equals不会进行类型转换。

4.java拆箱装箱实例2
        Integer l1=new Integer(127);
		Integer l2=new Integer(127);
		
		System.out.println(l1==l2);  //false
		System.out.println(l1.equals(l2));  //true

注意:new Integer()这种创建对象的方法不是自动装箱,没有用到内部缓冲区。因此i1==i2是false;

5.java拆箱装箱实例3
        Long l3=128L;
		Long l4=128L;
		
		System.out.println(l3==l4);  //false
		System.out.println(l3==128L);  //true
		
		Long l5=127L;
		Long l6=127L;
		
		System.out.println(l5==l6);   //true
		System.out.println(l6==127L);  //true
6.谈谈Integer i = new Integer(xxx)和Integer i =xxx;这两种方式的区别

1)第一种方式不会触发自动装箱的过程;而第二种方式会触发。
  2)在执行效率和资源占用上的区别。第二种方式的执行效率和资源占用在一般性情况下要优于第一种情况(注意这并不是绝对的)。

7.java语句Integeri=1;i+=1;做了哪些事情?

首先 Integer i = 1; 做了自动装箱(使用 Integer.valueOf() 方法将 int 装箱为 Integer 类型),接着 i += 1; 先将 Integer 类型的 i 自动拆箱成 int(使用Integer.intValue() 方法将 Integer 拆箱为 int),完成加法运行之后的 i 再装箱成 Integer 类型。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值