Skip to content

Commit 2062c3e

Browse files
committed
[fix] 整型包装类值的比较
1 parent ae531bf commit 2062c3e

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

docs/java/basis/Java基础知识疑难点.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -72,16 +72,16 @@ Reference:[Java中equals方法造成空指针异常的原因及解决方案](htt
7272
先看下面这个例子:
7373

7474
```java
75-
Integer x = 3;
76-
Integer y = 3;
77-
System.out.println(x == y);// true
78-
Integer a = new Integer(3);
79-
Integer b = new Integer(3);
80-
System.out.println(a == b);//false
81-
System.out.println(a.equals(b));//true
75+
Integer i1 = 40;
76+
Integer i2 = new Integer(40);
77+
System.out.println(i1==i2);//false
8278
```
8379

84-
当使用自动装箱方式创建一个Integer对象时,当数值在-128 ~127时,会将创建的 Integer 对象缓存起来,当下次再出现该数值时,直接从缓存中取出对应的Integer对象。所以上述代码中,x和y引用的是相同的Integer对象。
80+
`Integer i1=40` 这一行代码会发生拆箱,也就是说这行代码等价于 `Integer i1=Integer.valueOf(40)` 。因此,`i1` 直接使用的是常量池中的对象。而`Integer i1 = new Integer(40)` 会直接创建新的对象。因此,输出 false 。
81+
82+
记住:**所有整型包装类对象之间值的比较,全部使用 `equals()` 方法比较**
83+
84+
![](https://img-blog.csdnimg.cn/20210313164740893.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM0MzM3Mjcy,size_16,color_FFFFFF,t_70)
8585

8686
**注意:** 如果你的IDE(IDEA/Eclipse)上安装了阿里巴巴的p3c插件,这个插件如果检测到你用 ==的话会报错提示,推荐安装一个这个插件,很不错。
8787

0 commit comments

Comments
 (0)