Reputation: 756
I am trying to implement a reset function for a class and the easiest way to go about it would be to use removeAll()
on the arraylist and call the constructor. However that does not seem to work either because I have the wrong syntax for it for it I am trying something I can't do.
As of now I have a working method, but I would like to clean it up as it is just repeated code (All expect the removeAll()
statement) from the constructor which is called StandardDeck()
.
public void reset(){
cardArray.removeAll(cardArray);
for(int suit = 0; suit < 4; suit++){
for(int rank = 0; rank < 13; rank++){
PlayingCard card = new PlayingCard(suit, rank);
cardArray.add(card);
}
}
}
Upvotes: 1
Views: 4010
Reputation: 382150
If I understand well your need, you want this :
public class StandardDeck {
List<PlayingCard> cardArray = new ArrayList<>();
public StandardDeck() {
reset();
}
public void reset() {
cardArray.clear();
for(int suit = 0; suit < 4; suit++){
for(int rank = 0; rank < 13; rank++){
PlayingCard card = new PlayingCard(suit, rank);
cardArray.add(card);
}
}
}
}
No need to duplicate the loop. And as I pointed before clear is the standard and optimal solution to clear a list.
Upvotes: 3