Best way to increment Integer in arrayList in Java
You can't increment the value in place since Integer
objects are immutable. You'll have to get the previous value at a specific position in the ArrayList
, increment the value, and use it to replace the old value in that same position.
int index = 42; // whatever index
Integer value = ints.get(index); // get value
value = value + 1; // increment value
ints.set(index, value); // replace value
Alternatively, use a mutable integer type, like AtomicInteger
(or write your own).
Maybe you need to use another structure of data?
LinkedList<AtomicInteger> ints = new LinkedList<AtomicInteger>();
ints.add(new AtomicInteger(5));
ints.add(new AtomicInteger(9));
ints.getLast().incrementAndGet();