包装类的装箱和拆箱

你是否真的会用==?

下面是我从别处看到的两段小代码,方知我了解的只是皮毛中的皮毛;
代码一:Integer a=128,b=128;
Integer c=100,d=100;
System.out.println(a==b);//false
System.out.println(c==d);//true
结果为false和true;
原因:abcd都是新建的对象,而==是比较两个对象的引用,按理都是false;为什么第二个是true?当我们声明Integer c=100时,会进行自动装箱,也就是把基本数据类型转换为Integer类型的对象,而转换成Integer对象则是调用了valueOf()方法将Integer中-128-127的值缓存了下来,当声明的Integer对象的值在-128-127时,引用的是同一个对象,所以结果是true;
代码二:Integer a1 = new Integer(128);
int b1 = 128;
Integer c1 = new Integer(10);
Integer d1 = new Integer(10);
System.out.println(a1==b1);
System.out.println(c1==d1);
结果是:true和false
原因是:注意b1这里是int类型,当int和Integer进行==比较的时候,Java会把Integer进行自动拆箱,也就是把Integer转成int类型,所以这里进行比较的是int类型的值,所以结果即为true。而c1和d1是new出来的两个不同的对象,故为false。

String、Integer、int之间的转换

String 转int;调用Integer.parseInt(String str);常用
>
String s5 = “23”;
int i5 = Integer.parseInt(s5);//String转基本类型
int 转String;调用Integer.toString(int i);常用
>
int i4 = 200;
String s4 = Integer.toString(i4);//基本数据转String
String 转包装类
>
String s3 =”123”;
Integer i3 = new Integer(s3);//String转包装类
包装类 转String
>
Integer i2 = 10;
String s2 = i2.toString();//包装类转String
int 转包装类-装箱
Integer i = new Integer(10);//装箱
Integer i2 = 10;
int a1 = i2.intValue();//拆箱,也可以a1=i,自动拆箱

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值