I just have a quick question about iterators.
I currently want to remove items that are duplicates from two lists of objects.
The way I have it set up right now is that as long as the second list (the list of objects that need to be removed from the first list) has items, the loop which has does the merging will keep on running.
I have been using the hasNext() function to check if there are still items but I think there may be a slight problem with that.
When the iterator is pointing at the last item in the list and calls hasNext(), it will return false since there is nothing after the last item. This means that the item won’t be removed from the first list. Is that true?
Here’s the code:
for (Iterator<Card> discardItr = discard.iterator(); discardItr.hasNext();)
{
Card tempDiscard = discardItr.next();
Iterator<Card> mixedItr = mixedHand.iterator();
while (mixedItr.hasNext())
{
if (tempDiscard.equals(mixedItr.next()))
{
discardItr.remove();
mixedItr.remove();
}
}
}
An
Iteratorwill loop over the whole list, even when you calliterator#remove. For example runningproduces the following output
So your code will work (which you would of course have discovered by just trying it)