int与Integer的区别

int与Integer的区别:
最基本的区别:

(1)Integer是int的包装类;

(2)Integer是引用数据类型,int是基本数据类型。

(3) Integer可以赋值为null,int不可以;

(4)声明数组时int的初值为0,Integer的初值为null。

具体区别如下:

1,无论如何,Integer与new Integer不会相等。因为不会经历拆箱过程,new出来的对象存放在堆中,
 而非new的Integer常量则在常量池(在方法区),他们的内存地址不一样,所以为false。

2,两个都是非new出来的Integer,如果数在-128到127之间,则是true,否则为false。
 因为java在编译Integer i2 = 128的时候,被翻译成:
 Integer i2 = Integer.valueOf(128);
 而valueOf()函数会对-128到127之间的数进行缓存。

3,两个都是new出来的,都为false。还是内存地址不一样。

4,int和Integer(无论new否)比,都为true,因为会把Integer自动拆箱为int再去比。

示例:

	int num = 30;
	Integer numI1=new Integer(30);
	Integer numI2= new Integer(30);
	
	System.out.println(num == numI1); //true  Integer与int运算或赋值对应自动拆箱
	System.out.println(numI2 == numI1);//false
	
	//装箱:把基本数据类型转换成对应包装类
	//拆箱: 把包装类转换基本数据类型
	
	//装箱
	Integer numI3 = Integer.valueOf(50);
	
	//拆箱
	int num2 = numI1.intValue();  //Integer-->int
	byte bt = numI1.byteValue();  //Integer-->byte
	short st = numI1.shortValue(); //Integer-->short
	long lg = numI1.longValue(); //Integer-->long
	
	//------int与包装类Integer的区别----------
	int age =30;
	Integer ageI = null;  //Integer可以被赋为null,int不能赋值为null
	
	//用int,Integer定义数组的话,int初始值为0,Integer初始值为null
	int[] nums = new int[5];
	Integer[] numsI = new Integer[5];
	
	int no = -128;
	Integer no1 = -128;
	Integer no2 = -128; //如果赋值[-128-127]之间,第一个被赋值的变量,会有缓存。第二个变量直接取第一个变量的缓存
	Integer no3 = new Integer(-128);
	System.out.println(no==no1); //true
	System.out.println(no2==no1);//true
	System.out.println(no2==no3);//false
	System.out.println(no==no3);//true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值