Hello World

吞风吻雨葬落日 欺山赶海踏雪径

0%

JAVA自动装箱实例

JAVA自动装箱实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class AutoBoxing {
public static void main(String[] args) {
Integer a= 1;
Integer b= 2;
Integer c= 3;
Integer d= 3;
Long g = 3L;
Integer x= 128;
Integer y= 128;
System.out.println(c==d);
System.out.println(x==y);
System.out.println(c==(a+b));
System.out.println(c.equals(a+b));
System.out.println(g== (a+b));
System.out.println(g.equals(a+b));

}
}

在自动装箱时对于值从–128到127之间的值,它们被装箱为Integer对象后,会存在内存中被重用。
因为自动装箱的时候调用的是Integer.valueOf(),自动拆箱的时候调用的是Integer.intValue()

”==“在没有遇到运算符的时候不会自动拆箱,equals() 不会处理数据转型的关系

编译后:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class AutoBoxing
{
public static void main(String[] args)
{
Integer a = Integer.valueOf(1);
Integer b = Integer.valueOf(2);
Integer c = Integer.valueOf(3);
Integer d = Integer.valueOf(3);
Long g = Long.valueOf(3L);
Integer x = Integer.valueOf(128);
Integer y = Integer.valueOf(128);
System.out.println(c == d);
System.out.println(x == y);
System.out.println(c.intValue() == a.intValue() + b.intValue());
System.out.println(c.equals(Integer.valueOf(a.intValue() + b.intValue())));
System.out.println(g.longValue() == a.intValue() + b.intValue());
System.out.println(g.equals(Integer.valueOf(a.intValue() + b.intValue())));
}
}

输出:

1
2
3
4
5
6
true
false
true
true
true //注意这个是true, 说明 3l=1+2
false