It is not possible to assign values ββto the actual array that you are using in extended for each loop. This is because the extended for-each loop does not give you access to array pointers. To change the values ββof an array, you should literally say:
a[i] = anything
However, you can use the extended for-loop to assign values ββto another array as follows:
int[] nums = new int[4]; int[] setNums = {0,1,2,3}; i = 0; for(int e: setNums) { nums[i++] = e*2; }
Advanced for-loops in Java simply offer some syntactic sugar to get array or list values. In a sense, they work similarly to passing objects to a method - the original object passed to the method cannot be reassigned in the method. For instance:
int i = 1; void multiplyAndPrint(int p) { p = p*2; System.out.println(p); } System.out.println(i);
Will print 2, and then 1. This is the same problem that you will encounter trying to assign values ββfrom the for-each loop.
source share