0

我可以用 Iterator 类做什么?它说“DeckIterator 不是抽象的,并且不会覆盖 java.util.Iterator 中的抽象方法 remove()”

import java.util.*;
import java.io.Serializable;

public class Deck implements Iterable<Card>, Serializable {

// The field for a List
private List<Card> deck;

/**
 * Constructor creates the list, initializes all the cards in the deck and
 * shuffles them
 */
public Deck() {

    deck = new ArrayList<Card>();

    for (Card.Rank r : Card.Rank.values()) {
        for (Card.Suit s : Card.Suit.values()) {
            deck.add(new Card(r, s));
        }
    }

    shuffle();

    // Converting to a LinkedList
    List<Card> list = new LinkedList<Card>();
    for (int i = 0; i < deck.size(); i++) {
        list.add(deck.get(i));
    }
    deck = list;
}

/**
 * Method to randomize the cards
 */
public void shuffle() {

    Collections.shuffle(deck);
}

/**
 * Method that removes the top card from the deck
 *
 * @return the top card
 */
public Card deal() {

    return deck.remove(0);
}

/**
 * Number of cards remaining in the deck
 *
 * @return number of cards in the deck
 */
public int size() {

    return deck.size();
}

/**
 * Reinitializes the deck.
 */
public void newDeck() {

    List<Card> newList = new LinkedList<Card>();
    for (int i = 0; i < deck.size(); i++) {
        newList.add(deck.get(i));
    }
    deck = newList;

}

      public Iterator<Card> iterator(){

           Iterator<Card> aDeck = deck.iterator();
            return aDeck;
        }

它说“DeckIterator 不是抽象的,并且不会覆盖 java.util.Iterator 中的抽象方法 remove()”

public class DeckIterator implements Iterator<Card> {

    public List<Card> reverseIterator(){


        List<Card> reverseList = new LinkedList<Card>();
        for(int i = deck.size()-1; i >= 0; i--){
            reverseList.add(deck.get(i));
        }

        return reverseList;
    }

}


public static void main(String[] args){

    Deck myDeck = new Deck();
    System.out.println("The card " + myDeck.deal() + " is not in the deck now");

    }
}
4

1 回答 1

1

您的方法newDeck()应在添加新条目之前清除/清空列表。或者更确切地说,只是重新初始化deck为一个新的List. 事实上,构造函数中的大部分(全部?)代码都应该移到newDeck()方法中,构造函数可以简单地调用它。

于 2012-11-11T19:40:11.003 回答