英文:
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("元素在列表中不存在");
}
} else {
System.out.println("列表为空");
}
return first;
}
英文:
I don't know why find() method does not work for some numbers. Here is the code.
I'm talking about finding element in Double Linked List.
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;
}
答案1
得分: 0
很可能,你的问题出在:
if (tmp.element == o) {
return tmp;
}
这部分比较对象时使用的是引用相等性,而不是值相等性。你应该使用 .equals
进行比较。你提到它对某些数字起作用,我猜这意味着在你的测试中有一个 DLLNode<Integer>
- 你可能只是碰巧遇到了 JVM 缓存 Integer 对象的一个小子集(我想是在 -127 到 +128 之间),所以当使用 ==
时它们能够工作。
英文:
Most likely, your issue is with :
if (tmp.element == o) {
return tmp;
}
which is comparing objects using reference equality, not value equality. You want to use .equals
for that. You mention it works for some numbers, which I'm guessing means you have a DLLNode<Integer>
in your test - you're probably just running into the fact that the JVM caches a small subset of Integer objects (I think between -127 and +128) so those appear to work when using ==
.
答案2
得分: 0
你需要使用 equals
而不是 ==
==
比较的是引用,例如:
new Double(2d) == new Double(2d)
会返回 false,
但是 new Double(2d).equals(new Double(2d))
会返回 true。
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;
}
英文:
You need to use equals
instead of ==
==
compares references, ex:
new Double( 2d ) == new Double( 2d )
will be false,
but new Double( 2d ).equals(new Double( 2d ))
will be true.
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论