我有以下結構:for (String playerName: players)
。如何在不修改舊數組的情況下向數組添加元素或創建新數組?
我想循環所有players
加上一個更特殊的球員。但我不想通過向其添加新元素來修改players
陣列。那麼,我能做些什麼?
我可以用players
的所有元素加上一個元素來代替for (String playerName: players)
中的players
嗎?
我有以下結構:for (String playerName: players)
。如何在不修改舊數組的情況下向數組添加元素或創建新數組?
我想循環所有players
加上一個更特殊的球員。但我不想通過向其添加新元素來修改players
陣列。那麼,我能做些什麼?
我可以用players
的所有元素加上一個元素來代替for (String playerName: players)
中的players
嗎?
移動循環的內容中的另一種方法,並調用它內外:
for (String playerName : players) {
handlePlayer(playerName);
}
handlePlayer(anotherPlayerName);
+1:這是最簡單和恕我直言的最佳解決方案。沒有用於創建新列表或更改舊列表的開銷,它通過將代碼移入單獨的函數來改進代碼。 – dbemerlin 2010-03-22 14:47:05
@dbemerlin **開銷**創建一個新列表?可能會變得很小(可能在Apache Commons中用單對象開銷來實現) – 2010-03-22 14:51:06
我同意@Bozhos答案是最好的解決辦法。
但是,如果你絕對要使用一個循環,你可以使用Iterables.concat()
從Google Collectons(與Collections.singleton()
一起):
Iterable<String> allPlayersPlusOne=Iterables.concat(players,Collections.singleton(other));
for (String player : allPlayersPlusOne) {
//do stuff
}
我應該知道Google Collections已經完成了它。 – 2010-03-22 14:58:10
您可以創建Iterable'的'實現,但代碼是有點長,複雜。 – 2010-03-22 14:44:24