假设我正在玩一张包含一系列叠卡的纸牌游戏。我不知道游戏开始前会有多少张牌,但是一旦这样做,堆叠的牌的数量将保持不变。然后,我的第一个想法是使用我为游戏实例获得的堆栈数量创建一个数组,然后将这些堆栈中的每个顶层卡片放入数组中,然后使用链接列表将每张卡片链接到它们的堆栈。在Java中创建一组堆栈卡时替代链接列表?
我的卡类有以下字段:
public class Card {
private String suit;
private String value;
public Card cardInFront = null;
public Card cardInBack = null;
例如,让我们说我给出的标准一副扑克牌(52张牌,4套,13个值)被制作成5层。我分配在循环方式的前五个卡到5个开口的阵列,像这样:
int numOfPiles = 5;
Card[] cascadePiles = new Card[numOfPiles];
for (int i = 0; i < numOfPiles; i++) {
cascadePiles[i] = deck.get(i);
}
我再继续处理的循环方式的卡片,但连接每个卡我处理了与两个在它前面的卡和在它后面的卡。这一切都是用下面的代码完成:
int x = 0;
while (x != numOfPiles) {
deck.remove(0);
x++;
}
int i = 0;
while (!deck.isEmpty()) {
if (i < numOfPiles) {
Card cardBehind = cascadePiles[i];
Card temp = cascadePiles[i];
Card nullSearcher = cascadePiles[i].cardInFront;
while (nullSearcher != null) {
cardBehind = temp;
temp = nullSearcher;
nullSearcher = temp.cardInFront;
}
addToPile(temp, deck.get(0), cardBehind);
temp.cardIsInPile = PileType.CASCADE;
deck.remove(0);
i++;
} else {
i = 0;
}
}
这个原因,我所做的这一切在链表是因为我不知道有多少栈我需要每场比赛。如果我使用通用列表,我将不得不知道在游戏开始之前要声明多少个,我不知道。然而,通过像这样组织堆栈,我遇到了几个NullPointerException异常,并且我已经读过使用null,这通常是不好的习惯。有没有更聪明的方法来做到这一点?
为什么你不能使用'List []'?这会忽略'Card'中'cardInFront'和'cardInBack'引用的需要。 –
Turing85
即使你不知道有多少堆栈需要作为List支持add,remove等等,你也可以使用通用列表,并且你不需要传递大小给实现构造函数(例如'ArrayList' )预先 – niceman
反正你能告诉我们'deck'变量定义以及它的类/接口定义吗? – niceman