将整数与 == 进行比较究竟有什么作用?

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);

(猜到之后,运行看看!)

这篇关于将整数与 == 进行比较究竟有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:将整数与 == 进行比较究竟有什么作用?

基础教程推荐