In Java, I tried to change the value of a int (primitive type) array using the iterator. However, as you can see below, the iterator works fine when doing printing but it doesn't work to change the value of the int[]. While a simple for loop using index would do the job, I want to know why the for loop using iterator doesn't for changing value but does for printing. Thx
public class playGround {
public static void main(String[] args) {
int[] array = new int[5];
System.out.println("using iterable: ---");
for (int num : array) {
System.out.print(" " + num);
num = 2;
System.out.println(" " + num);
}
System.out.println(" after: ---");
for (int num : array) {
System.out.print(" " + num);
}
System.out.println();
System.out.println("using index: ---");
for (int i = 0; i < array.length ; i++) {
array[i] = i;
}
for (int num : array) {
System.out.print(" " + num);
}
}
}
output:
using iterable: ---
0 2
0 2
0 2
0 2
0 2
after: ---
0 0 0 0 0
using index: ---
0 1 2 3 4
Process finished with exit code 0