OCJP之Integer autoboxing


整形自动拆箱、自动装箱

1 对于[-128, 127]之间的整形,数是被缓存了,比较的是对象的值

2 上述范围之外的,比较的是对象,即地址

3 int与Integer比较,总是比较值。。。例如intValue()和Integer.valueOf()比较,应该是比较他们的值

4 Integer与Integer比较,看两个条件:

    1)是否有自动装箱,写成Integer i = 21,就会自动装箱成Integer;

        如Integer i1 = 21, Interger i2 = 21, then i1==i2 //true;

    2)值是否在[-128, 127]之间,自动装箱后,这个区间用的是缓存了的实例,简单理解成比较值;

       Integer i3 = 200, Interger i4 = 200; then i3==i4 //false;

    3)是否New出对象,

    如果有一个NEW出对象,也不可能相等,比较了地址;

    如果都没有NEW对象,直接写Integer i = 100;要判断值是否在[-128, 127]之间,如果在这个区间,就简单理解成直接比较值。。。

    Integer i5 = 21;

    Integer i6 = new Integer(21);

    i5==i6 //false;

    但是 21 == new Integer(21) //true, 适用于规则3;

public class IntegerMethod {
	public static void main(String[] args) {
		Integer i1 = 280;
		int i2 = 280;
		//left is int, right is Integer; 
		//Rule: when comparing int with Integer, it always compares their real values;
		System.out.println(i1.intValue()==Integer.valueOf(i2)); //output is true
		
		//when Integer.intValue() 在 [-128,128)范围内时,这个范围的对象被缓存了,直接比较值;
		Integer x = 127;
		Integer y = 127;
		System.out.println(x==y); //output: true
		
		//不在上述范围内,比较的是对象,是地址;
		Integer x1 = 129;
		Integer y1 = 129;
		System.out.println(x1==y1); //output: false
		
	}
	
}

例如:

package com.ocjp.basic;

public class AutoBoxing1 {
 public static void main(String[] args) {
	  Integer i1 = 2001; // set 1
	  Integer i2 = 2001;
	  System.out.println((i1 == i2) + " " + i1.equals(i2)); // output 1
	  Integer i3 = 21; // set 2
	  Integer i4 = new Integer(21);
//	  这一组最容易出错,i3用的是被缓存了的128内的Integer Instance,i4却是NEW出一个对象;它俩不等!!!
	  System.out.println((i3 == i4) + " " + i3.equals(i4)); // output 2
	  Integer i5 = 21; // set 3
	  Integer i6 = 21;
	  System.out.println((i5 == i6) + " " + i5.equals(i6)); // output 3
}
}

Output:

false true
false true
true true

例如:

package com.ocjp.basic;

public class AutoBoxing2 {
	public static void main(String[] args) {
		 String s = "";
		 System.out.println(Integer.parseInt("011")); //It always returns Decimal number;
		 if(Integer.parseInt("011") == Integer.parseInt("9")) s += 1;
//		 021 starting with 0, so it is Octal Number; Octal 021 = Decimal 17; 
		 if(021 == Integer.valueOf("17")) s += 2;
//		 When comparing int with Integer, it actually compares their values;
		 if(1024 == new Integer(1024)) s += 3;
		 System.out.println(s);
	}
}

输出:

11
23


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值