I mean in this code:
List<Integer> list = new LinkedList();
list.add(1);
list.add(2);
list.add(3);
for (Integer i : list)
i++;
System.out.println(list.get(0))
returns 1 not 2. In for-each loop Java creates new object (i) and copies fields value from object in List?
Integers are immutable.
Your code changes the i variable to point to a brand-new Integer instance with a larger value.
The original Integer instance in the list is not (and cannot be) changed.
the ++ operator is not a valid operator on the Integer object, so Java uses it's auto-boxing features to convert the Integer object into an int primitive. Once it's converted, the int primitive is incremented. You don't save the primitive so it is lost.
To achieve the goal you need to do something like
List<Integer> list = new LinkedList();
list.add(1);
list.add(2);
list.add(3);
for (int index; index < list.size(); index++) {
int value = list.get(index).intValue();
value++;
list.set(index, Integer.valueOf(value));
}
System.out.println(list.get(0))
The code above is not optimal; but it doesn't use autoboxing. An optimized solution would use a ListIterator (added by popular demand) :^)
ListIterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
iterator.set(iterator.get()++);
}
Note that this loop uses autoboxing heavily, if you wish to get an idea of what autoboxing is doing under the covers, the equivalent solution presented below doesn't rely on any autoboxing.
ListIterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
iterator.set(Integer.valueOf(iterator.get().intValue()++));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With