如何为一副牌创建自定义迭代器? (JAVA)

时间:2014-07-05 15:56:45

标签: java iterator

我正在尝试解决一个向我提供以下课程的问题。如何创建自定义迭代器类DeckIterator,它将帮助我迭代Deck类中的Card[] deck数组?

我有一个看起来像这样的Card类:

public class Card {

    private char suit;
    private int value;

    public Card (char s, int v)
    {
        this.suit = s;
        this.value = v;
    }
}

我有一个看起来像这样的Deck类:

public class Deck {

    private Card[] deck;
    private int idx;

    public Deck (int size) 
    {   
        this.deck = new Card[size];
        this.idx = 0;
    }
}

非常感谢

1 个答案:

答案 0 :(得分:1)

将其添加到课程Deck implements Iterable<Card>

public Card getCard( int i ){
    return deck[i];
}

public Iterator<Card> iterator(){
    return new DeckIterator( this );
}

public class DeckIterator implements Iterator<Card> {
    private Deck d;
    private int pos;
    DeckIterator( Deck d ){
        this.d = d;
    }

    @Override
    public boolean hasNext(){
        return pos < d.deck.length;
    }

    @Override
    public Card next(){
        if( pos >= d.deck.length ){
            throw new NoSuchElementException( "no more cards in deck" );
        }
        return d.getCard( pos++ );
    }

    @Override
    public void remove(){
        throw new UnsupportedOperationException( "not implemented" );
    }
}

套装可以作为枚举实现,也可以排名。