javaSE 包装类,自动装箱/拆箱。 byte范围内(-128~127)的数据在JVM中只存在一份


Demo.java:

package cn.xxx.demo;
/*
 *   JDK1.5后出现的特性,自动装箱和自动拆箱
 *   自动装箱: 基本数据类型,直接变成对象(引用类型)
 *   自动拆箱: 对象中的数据变回基本数据类型
 */
public class Demo {
	public static void main(String[] args) {
		function_2();
	}
	/*
	 *  关于自动装箱和拆箱一些题目
	 */
	public static void function_2(){
		Integer i = new Integer(1);
		Integer j = new Integer(1);
		System.out.println(i==j);// false 对象地址
		System.out.println(i.equals(j));// true  重写了Object的equals方法,比较的是对象数据
		
		System.out.println("===================");
		
		Integer a = 500;  // 大于127, 不在byte范围内。
		Integer b = 500;
		System.out.println(a==b);//false
		System.out.println(a.equals(b));//true
		
		System.out.println("===================");
		
		
		//数据在byte范围内(-128~127),JVM不会重新new对象。 byte范围内的数据在JVM中只存在一份。
		Integer aa = 127; // Integer aa = new Integer(127)
		Integer bb = 127; // Integer bb = aa;  127在byte范围内,128不在范围内
		System.out.println(aa==bb); //true
		System.out.println(aa.equals(bb));//true
	}
	
	
	//自动装箱和拆箱弊端,可能出现空指针异常
	public static void function_1(){
	    Integer in =null;	
	    //in = null.intValue()+1
	    in = in + 1;
	    System.out.println(in);
	}
	
	//自动装箱,拆箱的 好处: 基本类型和引用类直接运算
	public static void function(){
		//引用类型 , 引用变量一定指向对象
		//自动装箱, 基本数据类型1, 直接变成了对象
		
		Integer in = 1; // Integer in = new Integer(1)
		//in 是引用类型,不能和基本类型运算, 自动拆箱,引用类型in,转换成基本类型
		
		//in+1  ==> in.intValue()+1 = 2    
		// in = 2    自动装箱
		in = in + 1;  // 先自动拆箱,运算,再自动装箱
		
		System.out.println(in);
		
	}
}
/*
    ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(1);  // 自动装箱  1=>Integer
 */


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值