从Java的背面进行迭代时,为迭代器实现remove()

时间:2019-01-19 15:33:29

标签: java iterator

我想从列表的末尾进行迭代,然后针对我经历的每个项目将其删除。我想为迭代器实现remove(),但是不起作用。有人可以帮助我执行删除吗?到目前为止,这是我的代码,我删除了一些功能,以免造成混淆:

public class Deck implements Iterable <Card>{

static int count=0;
List<Card> cards;


public Deck(){
    cards = Arrays.asList(new Card[52]);
    Collections.shuffle(cards); //shuffles the cards in the deck
    System.out.println(cards);
    System.out.println("size:"+cards.size());
}

@Override
public Iterator<Card> iterator() {

    return new DeckIterator(cards);
}

//iterate ftom the last card to the the bottom card
private class DeckIterator implements Iterator<Card>{

    private int nextCard;
    private final List<Card> cards;
    boolean canRemove = false;
    private int nCards;

   public DeckIterator(List cards){
       this.cards=cards;
       this.nextCard = cards.size()-1;
       nCards = cards.size();
   }

    @Override
    public boolean hasNext() {
        if(cards.isEmpty() || nextCard<0){
            return false;
        }
        return true;
    }

   @Override
    public Card next() {
        Card temp;
        Iterator<Card> it = this.cards.iterator();
        if(hasNext()){
            temp = cards.get(nextCard--);
            canRemove = true;
            return temp;
        }
        return null;
    }

    //ITERATOR'S REMOVE 
    public void remove() {

    }
 }

  public static Card deal(Deck deck){
    Card topCard = null;
    int i=0;
    Iterator<Card> it = deck.iterator();
    Card temp;
    temp = it.next();
    while(it.hasNext() && i<count){
        temp = it.next();
    }
    it.remove();       //WHERE REMOVE IS BEING CALLED
    count++;

    return topCard;
}

public static void main (String[] argvs){

    Deck deck = new Deck();
    Iterator<Card> it = deck.iterator();

    while(it.hasNext()){
        System.out.println(it.next());

    }
    deal(deck);
    deal(deck);   
   }
}

1 个答案:

答案 0 :(得分:0)

您可以从List接口使用iterator()方法:

@Override
public Iterator<Card> iterator() {
     List<Card> newList = new ArrayList<>(this.cards); // copy to preserve original List order
     Collections.reverse(newList);
     return newList.iterator();
}

这样,您不必实现Iterator接口。