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());
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());
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;
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.
EDIT: wth, BigDecimal gave me the same kind of problem too.
EDIT 2: equals() worked, didn’t realize something else was amiss. Sorry.
You don’t want the != operator for this. It comapres references. You want the
.equals()method:Also, watch out for auto-boxing. You may find that
test.search(20.1)boxes 20.1 to aFloatnot aDouble, which will probably break your comparison. Compare the results withtest.search(20.1d). If I recall correctly, the expression:is false.