[英]why if comparison doesn't work in java
我在java中創建一個哈希表。 在搜索功能中,我在IF語句中進行了一些比較。 但它沒有做任何比較。
這是我的代碼的一部分。
while (table[pos]!=null) {
if (table[pos]==key) {
System.out.println("SEARCH "+key+" at INDEX "+home);
return;
}
else {pos=h(home+p(i));
i++;
}
}
System.out.println("Failed to find "+key+".");
return;
}
即使表[pos]和鍵是相同的,它也不起作用! 但我將非常簡單的賦值變量添加到另一個變量。 這行得通! 我不知道為什么會這樣。 我想知道它xD
while (table[pos]!=null) {
int x = table[pos];
if (x==key) {
System.out.println("SEARCH "+key+" at INDEX "+home);
return;
}
else {pos=h(home+p(i));
i++;
}
}
System.out.println("Failed to find "+key+".");
return;
}
好吧,如果table[pos]
和key
都是Integer
(並且table[pos]
必須是引用類型,因為你在while
語句中將它與null
進行比較),它們應該與equals
進行比較,而不是與==
進行比較,因為兩個不同的Integer
對象可能具有相同的int
值。
將table[pos]
分配給int
變量x
,它將取消框為原始值。
現在,當您將int
x
與Integer
key
進行比較時,該key
也將取消裝入int
,並且int
比較適用於==
。
這可以通過以下簡短示例來證明:
Integer i1 = 300;
Integer i2 = 300;
System.out.println (i1 == i2);
int i3 = i1;
System.out.println (i3 == i2);
哪個輸出:
false
true
代碼如下:
while (table[pos] != null) {
if (table[pos].equals(key)) {
System.out.println("SEARCH "+key+" at INDEX "+home);
return;
} else {
pos = h(home + p(i));
i++;
}
}
System.out.println("Failed to find "+key+".");
當使用==
比較兩個對象時,檢查這兩個引用是否指向內存中的相同位置,而使用==
with primitives只檢查值是否相同。 要正確檢查兩個Integers
內的值的等式,您應該使用equals()
方法。
在第二個示例中,您使用從Integer
取消裝箱到int
因此它按預期的方式檢查了值。 在第一個中,您比較了兩個值是否指向內存中的相同位置。
實際上正確的方法是使用兩者就像HashMap
一樣,這樣我們總是可以肯定的。 這是HashMap
在內部執行的示例:
if(((k = first.key) == key || (key != null && key.equals(k)))) ...
所以在你的情況下它將是:
if ((table[pos] == key) || (key != null && (table[pos].equals(key)))) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.