7

I don't understand why I cannot assign values to the elements of an array using the enhanced for loop. For example, using for loop like that

    int[] array = new int[5];
    for(int i = 0; i < 5; i++)
      array[i] = 10;

produces what I want. But why does that not work with "for each":

    for(int element : array)
      element = 10;

Is there any specific reason why that is the case or am I doing something wrong?

ActionField
  • 79
  • 1
  • 3

2 Answers2

10

In the enhanced for loop element is a local variable containing a reference (or value in case of primitives) to the current element of the array or Iterable you are iterating over.

Assigning to it doesn't affect the array / Iterable.

It's equivalent to :

int[] array = new int[5];
for(int i = 0; i < 5; i++) {
  int element = array[i];
  element = 10;
}

Which also won't modify the array.

If you need to modify the array, use should use a regular for loop.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

The enhanced for loop you use :

 for(int element : array)
  element = 10;
  1. In java we have references referencing an object. At a time one reference can reference to only one object. If it is made to reference another object then it losses the reference to the previous one. When you use = then you make element to reference another value i.e 10.

  2. Here element is of type int, which is primitive type. Even if it was an Integer then also Integer being immutable you would have not been able to make any modifications in the object as modifications always would have resulted in a separate object.

If it would have been the case as below for some Custom class say Student.java For some List<Student> students.

for(Student std : students){
    std.setName("eureka");
}

Now iterating the list and printing the name of each student would have resulted in printing eureka for each student. But note that even in this case use of = would have again produced same result as you are getting now (as again you would have referenced the variable to different object, it would no longer reference to the original object of the list).

nits.kk
  • 5,204
  • 4
  • 33
  • 55