我有一個必須完成一組任務的過程。該過程可能會嘗試嘗試已經完成的任務,在這種情況下,它應該忽略嘗試並生成完成其他任務的請求。我不確定追蹤哪些任務已完成,哪些仍需要處理的好方法。處理項目「檢查列表」的正確方法
我會用遊戲「Yahtzee」作爲例子來演示我目前如何處理這個。我首先創建的任務列表,在這種情況下,得分組合:
combinations = new ArrayList<String>();
combinations.add("one");
combinations.add("two");
...
combinations.add("fullhouse");
combinations.add("smallstraight");
combinations.add("yahtzee");
...
當玩家使用這些組合之一,我從ArrayList中刪除它,在這種情況下,「小直」組合:
public void selectSmallStraight() {
int index = combinations.indexOf("smallstraight");
if(index < 0)
System.out.println("Small Straight already used");
//Prompt the player for another selection
else
combinations.remove(index);
score += 30;
}
一旦使用了所有的組合,遊戲就結束了。
使用數組列表對我來說看起來很原始,更不用說醜陋了。我已經考慮過使用Map<String, Boolean>
,然後只要將它標記爲假,但我會認爲已經有一些「標準」的方式來做這件事更加優雅。
的主要問題我有一個ArrayList的方法是性能,就像你說。 – CalMlynarczyk
@Kededro因此,一個依賴HashMap的HashSet可以完成這項工作 – Omnaest