What can I do with Iterator class? It says “DeckIterator is not abstract and does not override abstract method remove() in java.util.Iterator”
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;
}
It says “DeckIterator is not abstract and does not override abstract method remove() in java.util.Iterator”
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");
}
}
Your method
newDeck()should clear/empty the list prior to adding new entries. Or rather just reinitialisedeckto a newList. In fact most (all?) of the code in the constructor should be moved to thenewDeck()method, and the constructor can simply call that.