我是靠谱客的博主 无私果汁,这篇文章主要介绍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;

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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 } }

例如:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

例如:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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


最后

以上就是无私果汁最近收集整理的关于OCJP之Integer autoboxing的全部内容,更多相关OCJP之Integer内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(63)

评论列表共有 0 条评论

立即
投稿
返回
顶部