What exactly does comparing Integers with == do?(将整数与 == 进行比较究竟有什么作用?)
问题描述
好的,好的,我看错了.我没有将 int 与 Integer 进行比较.适当注明.
OK, OK, I misread. I'm not comparing an int to an Integer. Duly noted.
我的 SCJP 书说:
My SCJP book says:
当 == 用于比较原语时对于包装器,包装器将是展开,比较将是原始到原始.
When == is used to compare a primitive to a wrapper, the wrapper will be unwrapped and the comparison will be primitive to primitive.
所以你会认为这段代码会打印 true
:
So you'd think this code would print true
:
Integer i1 = 1; //if this were int it'd be correct and behave as the book says.
Integer i2 = new Integer(1);
System.out.println(i1 == i2);
但它会打印 false
.
另外,根据我的书,这应该打印 true
:
Also, according to my book, this should print true
:
Integer i1 = 1000; //it does print `true` with i1 = 1000, but not i1 = 1, and one of the answers explained why.
Integer i2 = 1000;
System.out.println(i1 != i2);
不.这是假
.
什么给了?
推荐答案
Integer i1 = 1;
Integer i2 = new Integer(1);
System.out.println(i1 == i2);
当您将 1 分配给 i1
时,该值被装箱,创建一个 Integer
对象.比较然后比较两个对象引用.引用不相等,所以比较失败.
When you assign 1 to i1
that value is boxed, creating an Integer
object. The comparison then compares the two object references. The references are unequal, so the comparison fails.
Integer i1 = 100;
Integer i2 = 100;
System.out.println(i1 != i2);
因为这些是用编译时常量初始化的,所以编译器可以并且确实将它们内部化,并使它们都指向同一个 Integer
对象.
Because these are initialized with compile-time constants the compiler can and does intern them and makes both point to the same Integer
object.
(请注意,我将值从 1000 更改为 100.正如 @NullUserException 指出的那样,只保留小整数.)
(Note that I changed the values from 1000 to 100. As @NullUserException points out, only small integers are interned.)
这是一个非常有趣的测试.看看你能不能解决这个问题.为什么第一个程序打印true
,而第二个程序打印false
?使用您的装箱和编译器时间分析知识,您应该能够弄清楚:
Here's a really interesting test. See if you can figure this out. Why does the first program print true
, but the second one false
? Using your knowledge of boxing and compiler time analysis you should be able to figure this out:
// Prints "true".
int i1 = 1;
Integer i2 = new Integer(i1);
System.out.println(i1 == i2);
// Prints "false".
int i1 = 0;
Integer i2 = new Integer(i1);
i1 += 1;
System.out.println(i1 == i2);
<小时>
如果你理解了上面的内容,试着预测一下这个程序会打印什么:
If you understand the above, try to predict what this program prints:
int i1 = 0;
i1 += 1;
Integer i2 = new Integer(i1);
System.out.println(i1 == i2);
(猜到之后,运行看看!)
这篇关于将整数与 == 进行比较究竟有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将整数与 == 进行比较究竟有什么作用?
基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01