复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82public class JavaBase { public static void main(String[] args) { autoBoxing(); } /** * 装箱就是自动将基本数据类型转换为包装器类型(int-->Integer);调用方法:Integer的 * valueOf(int) 方法 * 拆箱就是自动将包装器类型转换为基本数据类型(Integer-->int)。调用方法:Integer的intValue方 法 */ public static void autoBoxing(){ Integer a1 = new Integer(127); //jdk 1.5 之前 Integer a = 127; //jdk 1.5以后 Integer b = 127; Integer c = 128; Integer d = 128; System.out.println(a1 == a);//false System.out.println(a == b); //true 原因在:Integer.valueOf()方法 -128 ~127 会缓存起来 System.out.println(c == d); //false Integer.valueOf(127); Integer.valueOf(-128); /** * public static Integer valueOf(int i) { * if (i >= IntegerCache.low && i <= IntegerCache.high) * return IntegerCache.cache[i + (-IntegerCache.low)]; * return new Integer(i); * } */ /** * public static Integer valueOf(int i) { * if (i >= IntegerCache.low && i <= IntegerCache.high) * return IntegerCache.cache[i + (-IntegerCache.low)]; * return new Integer(i); * } */ Long l1 = 127L; Long l2 = 127L; Long l3 = 128L; Long l4 = 128L; System.out.println(l1 == l2); //true System.out.println(l3 == l4); //false Long.valueOf(127); Long.valueOf(-128); /** *public static Long valueOf(long l) { * final int offset = 128; * if (l >= -128 && l <= 127) { // will cache * return LongCache.cache[(int)l + offset]; * } * return new Long(l); * } */ Double d1 = 127.0; Double d2 = 127.0; Double d3 = 128.0; Double d4 = 128.0; Double.valueOf(127.0); //原因: 在某个范围内的整型数值的个数是有限的,而浮点数却不是。所有没有缓存 /** * public static Double valueOf(double d) { * return new Double(d); * } */ System.out.println(d1 == d2); //false System.out.println(d3 == d4); //false } }
最后
以上就是高贵龙猫最近收集整理的关于java基础之基础类型的自动装箱的全部内容,更多相关java基础之基础类型内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复