首先 make Deck
implement Iterable<Card>
,这将要求您实现该iterator()
方法。使该方法返回嵌套DeckIterator
类的实例。
@Override
public Iterator<Card> iterator()
{
return new DeckIterator(deck);
}
然后DeckIterator
实现Iterator<Card>
并实现hasNext()
,next()
和remove()
方法。
private static class DeckIterator implements Iterator<Card>
{
private int nextCard;
private final List<Card> cards;
public DeckIterator(List<Card> cards)
{
this.cards = cards;
this.nextCard = cards.size() - 1;
}
@Override
public boolean hasNext()
{
if (nextCard < 0)
return false;
return true;
}
/**
* {@inheritDoc}
*/
@Override
public Card next()
{
if (hasNext())
return cards.get(nextCard--);
return null;
}
/**
* {@inheritDoc}
*/
@Override
public void remove()
{
}
}
然后使用,
Iterator<Card> iterator = yourDeck.iterator();
while (iterator.hasNext())
{
Card card = iterator.next();
}
在甲板上向后迭代。
Iterator
但是,如果您只想反向迭代,则不需要创建自己的ListIterator
可以为您完成。
ArrayList<Card> deck = new ArrayList<Card>();
// Do whatever you do with your deck :P
ListIterator<Card> li = deck.listIterator(deck.size());
// Iterate in reverse.
while(li.hasPrevious())
{
Card card = li.previous();
// Do stuff with the card
}