tags:

views:

87

answers:

2

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 containing all elements of the players plus one more element?

+8  A: 

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

for (String playerName : players) {
    handlePlayer(playerName);
}
handlePlayer(anotherPlayerName);
Bozho
+1: This is the easiest and IMHO best solution. No overhead for creating a new list or changing the old one and it improves the code by moving code into a seperate function.
dbemerlin
@dbemerlin **Overhead** in creating a new list?? Probably going to be tiny (probably something in Apache Commons to do it with single-object overhead)
Tom Hawtin - tackline
+3  A: 

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
}
Joachim Sauer
I should have known Google Collections had already done it.
Michael Myers