在Java中使用==运算符来比较包装器对象 [英] Using == operator in Java to compare wrapper objects

查看:80
本文介绍了在Java中使用==运算符来比较包装器对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Kathy Sierra和Bert Bates的SCJP Java 6,这本书让我非常困惑。在页245上,他们说明下面的代码。

I'm reading SCJP Java 6 by Kathy Sierra and Bert Bates and this book is confusing me so much. On page 245 they state that the following code below.

Integer i1 = 1000;
Integer i2 = 1000;
if(i1 != i2)
System.out.println("different objects");

//Prints output
different objects

然后在下一页他们有以下代码

Then on the very next page they have the following code

Integer i3 = 10;
Integer i4 = 10;
if(i3 == i4)
System.out.println("same objects");

//Prints output
same objects

我是如此迷茫!当我自己尝试这个时,似乎你不能使用==来比较你使用equals()方法的方式。即使整数变量设置为相同的值(即10),使用==总是给我'假'。我对么?使用==来比较相同的Integer对象(具有相同的值)将始终导致'false'

I'm so confused! When I try this out on my own it seems that you cannot use the == to compare the same way you would use equals() method. Using the == always gives me 'false' even if the Integer variables are set to the same value (i.e. 10). Am I correct? Using the == to compare the same Integer object (with same values) will always result in 'false'

推荐答案

关键是答案称为对象实习。 Java实习小数(小于128),因此所有 Integer(n)的实例在实习范围内具有 n 是相同的。大于或等于128的数字不会被实习,因此整数(1000)对象彼此不相等。

The key to the answer is called object interning. Java interns small numbers (less than 128), so all instances of Integer(n) with n in the interned range are the same. Numbers greater than or equal to 128 are not interned, hence Integer(1000) objects are not equal to each other.

这篇关于在Java中使用==运算符来比较包装器对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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