// primitive type in for-each int[] array1 = newint[3]; for (int value : array1) { value = 1; } for (int value : array1) { System.out.print(value + " "); } // output: 0 0 0
Change of Reference Type
与原生类型相反,对引用类型的数组或容器使用for-each进行遍历,可以改变原数组或容器内元素的值
1 2 3 4 5 6
classNico { int i; Nico (int i) { this.i = i; } }
1 2 3 4 5 6 7 8 9 10 11 12
// change of reference type in for-each Nico[] array2 = newNico[3]; for (inti=0; i < array2.length; ++i) { array2[i] = newNico(i); } for (Nico value : array2) { value.i = 25252; } for (Nico value : array2) { System.out.print(value.i + " "); } // output: 25252 25252 25252
// assignment of reference type in for-each Nico[] array3 = newNico[3]; for (Nico value : array3) { value = newNico(25252); } for (Nico value : array3) { System.out.print(value + " "); } // output: null null null