我正在尝试解决一个向我提供以下课程的问题。如何创建自定义迭代器类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;
}
}
非常感谢
答案 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" );
}
}
套装可以作为枚举实现,也可以排名。