我创建了一个链表,具有插入、搜索和删除功能。我还为它创建了一个迭代器。现在,假设我这样做:
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)。现在,如果我这样做:
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。下面是搜索功能的实现:
public iterator search(T data)
{
no<T> temp = first;
while( (temp != null) && (temp.data != data) )
temp = temp.next;
return (new iterator(temp));
}
我是这样知道比较有问题的:如果我像这样更改上面的部分代码:
while( (temp != null) && (temp.data != data) )
System.out.println(temp.data + " " + data);
temp = temp.next;
我可以看到它打印了列表中的数字。它会在某一时刻打印“20.1 20.1”(例如)。那么我该如何解决呢?该函数似乎是正确的,但似乎 Java 没有正确比较数字。
编辑:BigDecimal 也给了我同样的问题。
编辑 2:equals() 起作用了,没有意识到其他地方不对劲。对不起。
最佳答案
请注意,使用 .equals()
比较 doubles 可能会导致错误。 Double.equals()
将其用作相等性测试:
d1.doubleValue() == d2.doubleValue()
double 和 float 是存储在内存固定空间中的数字的近似值。
为了正确比较 float ,您需要注意,由于 float 的性质,会出现一些错误。
参见:http://www.google.com/search?q=floating+point+equality
比较 double 的一种快速简便的方法是使用 Math.abs(a-b)<ACCEPTABLE_ERROR
其中 ACCEPTABLE_ERROR 可能是 .000000000001
取决于你到底在做什么。
(注意这不处理 NaN 和 INFINITY 等边缘情况)
关于Java 似乎没有正确比较 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/393366/