The enhanced for loop can only retrieve the collection, but cannot update it
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
for (Integer integer:list) {
integer = 5;
System.out.println(integer+" ");
}
System.out.println(list);
The integer is changed in the loop, but the list is not changed after the loop.
The reason is that integer is a reference to the object in the list, integer = 5; it just points the reference of integer to 5, and does not make any changes to the list.
If there is a need to make an update, you can use the method of array replacement, as follows
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
for (int i = 0; i < list.size(); i++) {
list.set(i,5) ;
}
System.out.println(list);