I have a class ‘Deck’, that creates an ArrayList called deck.
I’m trying to create a nested Iterator class that traverses the Cards in reverse order.
public class Deck {
//Nested Iterator class to traverse the Cards in reverse order
public abstract class DeckIterator implements Iterator<Card>{
ListIterator it = deck.listIterator(deck.size());
//Iterate in reverse.
while(it.hasPrevious()) { //errors
//System.out.println(it.previous());
return it.previous();
}
}
}
I have tried the suggestions below but I am still having no luck…
Instead of copying One ArrayList to another in reverse order, i’d rather Iterate over the existing ArrayList in the Outer Class. What is the most efficient way of doing this?
Firstly make
DeckimplementIterable<Card>, this will require you to implement theiterator()method. Make that method return an instance of your nestedDeckIteratorclass.Then make
DeckIteratorimplementIterator<Card>and implement thehasNext(),next()andremove()methods.Then use,
To iterate backwards over the deck.
However you dont need to create your own
Iteratorif you just want to iterate in reverseListIteratorcan do it for you.