Java似乎没有正确比较Doubles [英] Java doesn't seem to be comparing Doubles right
问题描述
我创建了一个链接列表,具有插入,搜索和删除功能。我也为它创建了一个迭代器。现在,假设我这样做:
I created a Linked List, with insert, search and remove functions. I also created a iterator for it. Now, suppose I do this:
myList<Integer> test = new myList();
test.insert(30);
test.insert(20);
test.insert(10);
myList.iterator it = test.search(20);
if(it.hasNext())
System.out.println(it.next());
而且,它可以工作(它打印节点上元素的值,在这种情况下为20 )。现在,如果我这样做:
And voila, it works (it prints the value of the element at the node, in this case 20). Now, if I do this:
myList<Double> test = new myList();
test.insert(30.1);
test.insert(20.1);
test.insert(10.1);
myList.iterator it = test.search(20.1);
if(it.hasNext())
System.out.println(it.next());
它没有,因为迭代器指向null。这是搜索功能的实现:
It doesn't, because the iterator is pointing to null. Here is the implementation of the search function:
public iterator search(T data)
{
no<T> temp = first;
while( (temp != null) && (temp.data != data) )
temp = temp.next;
return (new iterator(temp));
}
以下是我如何知道有什么比较的东西:如果我更改部分上面的代码如下:
Here's how I know there's something fishy with the comparisons: If I change part of the above code like this:
while( (temp != null) && (temp.data != data) )
System.out.println(temp.data + " " + data);
temp = temp.next;
我可以看到它打印列表中的数字。它在一点打印20.1 20.1(例如)。那我该怎么解决呢?该函数似乎是正确的,但它似乎好像Java不正确比较数字。
I can see it printing the numbers in the list. It prints, at one point, "20.1 20.1" (for example). So how can I fix this? The function appears to be right, but it just seems as if Java isn't comparing the numbers correctly.
编辑:wth,BigDecimal也给了我同样的问题。
wth, BigDecimal gave me the same kind of problem too.
编辑2:等于()工作,没有意识到别的东西是不幸的。对不起,
EDIT 2: equals() worked, didn't realize something else was amiss. Sorry.
推荐答案
你不需要这个!=操作符。它映射参考。你想要 .equals()
方法:
You don't want the != operator for this. It comapres references. You want the .equals()
method:
public iterator search(T data)
{
no<T> temp = first;
while (!data.equals(temp.data)) {
temp = temp.next;
}
return (new iterator(temp));
}
另外,注意自动拳击。您可能会发现 test.search(20.1)
框20.1至浮动
不是双
,这可能会打破你的比较。将结果与 test.search(20.1d)
进行比较。如果我记得正确,表达式:
Also, watch out for auto-boxing. You may find that test.search(20.1)
boxes 20.1 to a Float
not a Double
, which will probably break your comparison. Compare the results with test.search(20.1d)
. If I recall correctly, the expression:
new Float(20.1).equals(new Double(20.1))
为假。
这篇关于Java似乎没有正确比较Doubles的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!