JAVA学习-自动装箱与拆箱

装箱:自动将基本数据类型转换为包装器类型
拆箱:自动将包装器类型转换为基本数据类型

intInteger 举例:

Integer i = 77;
//Integer i = 77; 就是一个装箱的过程,相当于Integer i = Integer.valueOf(77);
int i2 = i;
//int i2 = i; 就是一个拆箱的过程,相当于 int i2 = i.intValue();

需要注意的几点是:

  1. -128 ~ 127 的整数会进行缓存,因此在定义两个以上对象时,若值相等且范围在 -128 ~ 127 之间,则 Java就会返回相同的地址,若超过这个返回,就会新建一个对象。byte,short,int,long都是如此,不过 byte 就是它本身的范围罢了。
  2. '\u0000' ~ '\u007f' 的字符型。
  3. 布尔类型的值都会缓存
  4. 浮点型都是返回新的对象
Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
System.out.println(a == b);    // true
System.out.println(c == d);    // false
Character a = '\u007f';
Character b = '\u007f';
Character c = '\u0080';
Character d = '\u0080';
System.out.println(a == b);    // true
System.out.println(c == d);    // false
Boolean a = true;
Boolean b = true;
Boolean c = false;
Boolean d = false;
System.out.println(a == b);    // true
System.out.println(c == d);    // true
Double a = 127.0;
Double b = 127.0;
Double c = 128.0;
Double d = 128.0;
System.out.println(a == b);    // false
System.out.println(c == d);    // false

相关方法:a.equals(b)a == bObjects.equals(a, b):

  1. a.equals(b) 不比较对象的地址,只要 a,b 类型相同并且值相等,该方法就返回真,但注意 a 不能为空
  2. a == b 在 a,b 为基本数据类型时,比较的是数据的大小;在 a,b 引用类型时,比较的是引用类型中存放的地址。
  3. Objects.equals(a, b) 和 a.equals(b) 类似,不同的是 a 为空时也可以比较,都为空返回真,一个为空返回假。使用时需要导入 java.util.Objects 包。
Integer a = 128;
Integer b = 128;
Integer c = null;
Integer d = null;

System.out.println(a.equals(b));	        // true
System.out.println(a == b);		            // false
System.out.println(Objects.equals(a, b));	// true

//System.out.println(c.equals(d));	        // java.lang.NullPointerException
System.out.println(c == d);		            // true
System.out.println(Objects.equals(c, d));	// true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

什巳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值