問(wèn)題描述
下面的代碼讓我很困惑,因?yàn)樗峁┝藘煞N不同的輸出.代碼在 jdk 1.7 上測(cè)試過(guò).
The following code seemed really confusing to me since it provided two different outputs.The code was tested on jdk 1.7.
public class NotEq {
public static void main(String[] args) {
ver1();
System.out.println();
ver2();
}
public static void ver1() {
Integer a = 128;
Integer b = 128;
if (a == b) {
System.out.println("Equal Object");
}
if (a != b) {
System.out.println("Different objects");
}
if (a.equals(b)) {
System.out.println("Meaningfully equal.");
}
}
public static void ver2() {
Integer i1 = 127;
Integer i2 = 127;
if (i1 == i2) {
System.out.println("Equal Object");
}
if (i1 != i2){
System.out.println("Different objects");
}
if (i1.equals(i2)){
System.out.println("Meaningfully equal");
}
}
}
輸出:
[ver1 輸出]
不同的對(duì)象
有意義的平等.
[ver1 output]
Different objects
Meaningfully equal.
[ver2 輸出]
相等對(duì)象
有意義的平等
[ver2 output]
Equal Object
Meaningfully equal
為什么 == 和 != 測(cè)試會(huì)為 ver1() 和 ver2() 生成不同的結(jié)果,而相同的數(shù)字遠(yuǎn)小于 Integer.MAX_VALUE?是否可以斷定 == 檢查大于 127 的數(shù)字(對(duì)于像代碼中顯示的 Integer 這樣的包裝類)完全是浪費(fèi)時(shí)間?
Why the == and != testing produces different results for ver1() and ver2() for same number much less than the Integer.MAX_VALUE? Can it be concluded that == checking for numbers greater than 127 (for wrapper classes like Integer as shown in the code) is totally waste of time?
推薦答案
為 -128 和 127 之間的值緩存整數(shù),因此 Integer i = 127
將始終返回相同的引用.Integer j = 128
不一定會(huì)這樣做.然后,您將需要使用 equals
來(lái)測(cè)試底層 int
的相等性.
Integers are cached for values between -128 and 127 so Integer i = 127
will always return the same reference. Integer j = 128
will not necessarily do so. You will then need to use equals
to test for equality of the underlying int
.
這是 Java 語(yǔ)言規(guī)范:
如果被裝箱的值 p 是真、假、一個(gè)字節(jié)或 u0000 到 u007f 范圍內(nèi)的一個(gè)字符,或者一個(gè)介于 -128 和 127(包括)之間的 int 或短數(shù)字,則令 r1 和 r2 為p 的任意兩次裝箱轉(zhuǎn)換的結(jié)果.r1 == r2 總是如此.
If the value p being boxed is true, false, a byte, or a char in the range u0000 to u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
但是對(duì) Integer j = 128
的 2 次調(diào)用可能會(huì)返回相同的引用(不保證):
But 2 calls to Integer j = 128
might return the same reference (not guaranteed):
例如,內(nèi)存限制較少的實(shí)現(xiàn)可能會(huì)緩存所有 char 和 short 值,以及 -32K 到 +32K 范圍內(nèi)的 int 和 long 值.
Less memory-limited implementations might, for example, cache all char and short values, as well as int and long values in the range of -32K to +32K.
這篇關(guān)于!= 和 == 運(yùn)算符如何處理 Java 中的整數(shù)?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!