java中装箱和拆箱

public class Student {
	public static void main(String[] args) {
		//自动装箱
		Integer a = 6;
		
		//自动拆箱
		int b = a;
	}
}

上边两行代码就是自动装箱和拆箱,简单来说就是:装箱就是自动将基本数据类型转换为包装器类型;拆箱就是自动将包装器类型转换为基本数据类型。

下面我们来看看需要装箱拆箱的类型有哪些:也就是基本数据类型对应的包装类:

è¿éåå¾çæè¿°

下面通过几个例子了解一下包装类。

第一个:看到这个程序,第一时间想这还用判断?肯定是错,因为==如果是对象则比较地址,现在两个新对象肯定分配的地址不一样呀。但是结果是true。

	public static void main(String[] args) {
		//自动装箱
		Integer a = 6;
		Integer b = 6;
		System.out.println(a == b);
	}

打开Integer源码发现:

/**
 * Returns an {@code Integer} instance representing the specified
 * {@code int} value.  If a new {@code Integer} instance is not
 * required, this method should generally be used in preference to
 * the constructor {@link #Integer(int)}, as this method is likely
 * to yield significantly better space and time performance by
 * caching frequently requested values.
 *
 * This method will always cache values in the range -128 to 127,//这个范围内,自动放在常量池中
 * inclusive, and may cache other values outside of this range.
 *
 * @param  i an {@code int} value.
 * @return an {@code Integer} instance representing {@code i}.
 * @since  1.5
 */
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

This method will always cache values in the range -128 to 127,//这个范围内,自动放在常量池中,所以是一个地址,当然是true。

第二个:当包装类和基本数据类型做比较,则包装类自动拆箱:

	public static void main(String[] args) {
		//自动装箱
		Integer a = 128;
		int b = 128;
		System.out.println(a == b);
	}

文本所用的==和equals方法总结

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值