問題描述
我不知道為什么這些代碼行返回不同的值:
I have no idea why these lines of code return different values:
System.out.println(Integer.valueOf("127")==Integer.valueOf("127"));
System.out.println(Integer.valueOf("128")==Integer.valueOf("128"));
System.out.println(Integer.parseInt("128")==Integer.valueOf("128"));
輸出是:
true
false
true
為什么第一個返回true
,第二個返回false
?127
和 128
之間有什么我不知道的不同之處嗎?(當然我知道127
< 128
.)
Why does the first one return true
and the second one return false
? Is there something different that I don't know between 127
and 128
? (Of course I know that 127
< 128
.)
還有,為什么第三個返回true
?
Also, why does the third one return true
?
我已閱讀這個問題的答案,但我還是沒搞懂怎么返回true
,為什么第二行的代碼返回false
.
I have read the answer of this question, but I still didn't get how it can return true
, and why the code in second line returns false
.
推薦答案
這里有一個顯著的區別.
There's a striking difference here.
valueOf
正在返回一個 Integer
對象,該對象的值可能緩存在 -128 和 127 之間.這就是第一個值返回 true
- 它已緩存 - 第二個值返回 false
- 128 不是緩存值,因此您將獲得兩個單獨的 Integer
實例.
valueOf
is returning an Integer
object, which may have its values cached between -128 and 127. This is why the first value returns true
- it's cached - and the second value returns false
- 128 isn't a cached value, so you're getting two separate Integer
instances.
請務必注意,您將引用與 Integer#valueOf
進行比較,如果您比較的值大于緩存支持的值,它將not 評估為 true
,即使解析的值是等價的(例如:Integer.valueOf(128) == Integer.valueOf(128)代碼>).您必須改用
equals()
.
It is important to note that you are comparing references with Integer#valueOf
, and if you are comparing a value that is larger than what the cache supports, it will not evaluate to true
, even if the parsed values are equivalent (case in point: Integer.valueOf(128) == Integer.valueOf(128)
). You must use equals()
instead.
parseInt
正在返回一個原始 int
.這就是為什么第三個值返回 true
- 128 == 128
被評估,當然是 true
.
parseInt
is returning a primitive int
. This is why the third value returns true
- 128 == 128
is evaluated, and is of course, true
.
現在,恰好使第三個結果 true
:
Now, a fair bit happens to make that third result true
:
一個拆箱轉換發生在 您正在使用的等價運算符和您擁有的數據類型 - 即
int
和Integer
.當然,您會從右側的valueOf
獲得一個Integer
.
An unboxing conversion occurs with respect to the equivalence operator you're using and the datatypes you have - namely,
int
andInteger
. You're getting anInteger
fromvalueOf
on the right hand side, of course.
轉換后,您將比較兩個原始 int
值.比較會按照您對原語的預期進行,因此您最終會比較 128
和 128
.
After the conversion, you're comparing two primitive int
values. Comparison happens just as you would expect it to with respect to primitives, so you wind up comparing 128
and 128
.
這篇關于為什么 == 與 Integer.valueOf(String) 的比較對 127 和 128 給出不同的結果?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!