Reputation: 301
The below iterator class return all of the elements except the first, and the last element it returns is null. I'm not sure how to fix it so that it just returns all the elements with no null value in the end.
Upvotes: 0
Views: 104
Reputation: 116306
Here
newHead = newHead.next;
...
return (E) newHead;
you move to the next element, then return its contents. In effect you always skip the very first element of the list. Do it instead the other way around (using a temporary variable):
MyListNode<E> current = newHead;
newHead = newHead.next;
...
return (E) current;
Upvotes: 1
Reputation: 56
Your returning null in your next method.
when you call the iterator you can use the hasNext method check before using next. That way it shouldn't add the extra null at the end.
while(iterator.hasNext()) {
//add to list
}
Upvotes: 0