开发者

How to add an element to an array without a modification of the old array or creation a new one?

I have the following construction: for (String playerName: players).

I would like to make a loop over all players plus one more special player. But I do not want to modify the players array by adding a new element to it. So, what can I do?

Can I replace players in the for (String playerName: players) by something c开发者_高级运维ontaining all elements of the players plus one more element?


Move the contents of the loop in another method, and call it both inside and outside:

for (String playerName : players) {
    handlePlayer(playerName);
}
handlePlayer(anotherPlayerName);


I agree that @Bozhos answer is the best solution.

But if you absolutely want to use a single loop, you can use Iterables.concat() from Google Collectons (together with Collections.singleton()):

Iterable<String> allPlayersPlusOne=Iterables.concat(players,Collections.singleton(other));
for (String player : allPlayersPlusOne) {
  //do stuff
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜