2

Why for-each loop in java can't be used for assignments? For eg I am trying the below example and not getting the expected result but compiles successfully:

int count = 0;
String[] obj = new String[3];
for (String ob : obj )
   ob = new String("obj" + count++);

System.out.println(obj[0]);    // null
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
Swaroop Nagendra
  • 609
  • 2
  • 15
  • 25

3 Answers3

2

ob is a local variable which is a copy of the reference in the array. You can alter it but it doesn't alter the array or collection it comes from.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

Essentially, that is correct. The for-each loop is not usable for loops where you need to replace elements in a list or array as you traverse it

String[] obj = { "obj1", "obj2", "obj3" };

or

for (int count = 0; count < obj.length; count++) {
    obj[count] = "obj" + count;   
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

As you've noted, you can't use the variable in an array iteration to set the values of the array. In fact your code, while legal, is unusual in iterating through the elements of an array in order to initialise them. As other answers have noted, you are better off using the index of the array.

Even better is to create the array in the process of initialisation. For example, in Java 8 you could use:

String[] obj = IntStream.range(0, 4).mapToObj(n -> "obj" + n).toArray();

This seems to me to capture your intent of creating strings and then turning them into a new array rather than create an array and then iterate through it changing each element.

sprinter
  • 27,148
  • 6
  • 47
  • 78