什么比较整数与==做什么? [英] What exactly does comparing Integers with == do?

查看:134
本文介绍了什么比较整数与==做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:OK,OK,我误读了。我不是一个int比较整数。已正式注明。

OK, OK, I misread. I'm not comparing an int to an Integer. Duly noted.

我的SCJP图书说:


为了比较一个原始的
和一个包装,包装将是
unwrapped和比较将
原始到原始。

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

不适用。 false

有什么作用?

推荐答案

Integer i1 = 1;
Integer i2 = new Integer(1);
System.out.println(i1 == i2);

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

(猜猜后,运行它并查看!

这篇关于什么比较整数与==做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆