[英]Find Method in Linked List does not work with some numbers
我不知道為什么 find() 方法對某些數字不起作用。 這是代碼。 我說的是在雙鏈表中查找元素。
public DLLNode<E> find(E o) {
if (first != null) {
DLLNode<E> tmp = first;
while (tmp.element != o && tmp.succ != null)
tmp = tmp.succ;
if (tmp.element == o) {
return tmp;
} else {
System.out.println("Element does not exist in a list");
}
} else {
System.out.println("List is empty");
}
return first;
}
最有可能的是,您的問題是:
if (tmp.element == o) {
return tmp;
}
這是使用引用相等而不是值相等來比較對象。 您想為此使用.equals
。 您提到它適用於某些數字,我猜這意味着您的測試中有一個DLLNode<Integer>
- 您可能只是遇到了這樣一個事實,即 JVM 緩存了 Integer 對象的一小部分(我認為在 -127和 +128) 所以這些在使用==
時似乎有效。
您需要使用equals
而不是==
==
比較引用,例如:
new Double( 2d ) == new Double( 2d )
將是假的,
但new Double( 2d ).equals(new Double( 2d ))
將為真。
public DLLNode<E> find(E o) {
if (first != null) {
DLLNode<E> tmp = first;
while (!tmp.element.equals(o) && tmp.succ != null)
tmp = tmp.succ;
if (tmp.element.equals(o)) {
return tmp;
} else {
System.out.println("Element does not exist in a list");
}
} else {
System.out.println("List is empty");
}
return first;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.