[英]Calling constructor from method inside class
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. 我正在尝试为类实现重置函数,最简单的方法是在arraylist上使用removeAll()
并调用构造函数。 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()
. 到目前为止,我有一个工作方法,但我想清理它,因为它只是重复代码(所有期望removeAll()
语句)来自构造函数,称为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);
}
}
}
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. 正如我之前指出明确的标准和最佳的解决方案,以清除列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.