What is the cleanest way to increment an Integer in an ArrayList?
ArrayList<Integer> ints = new ArrayList<>();
ints.add(5);
ints.add(9);
What is the cleanest way to increment the last element?
ints.set(ints.size() - 1, ints.get(ints.size() - 1) + 1);
seems pretty ugly to me.
However, ensureCapacity() method of java. util. ArrayList class can be used to increase the capacity of an ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
In order to optimize the performance of ArrayLists, it is advisable to set a large enough initial capacity when initializing an ArrayList to incorporate all your data. This will allocate a large enough chunk of memory so that you will probably not need to perform the allocation process again.
We cannot specify int as the type of an ArrayList. An int is not a "ReferenceType." Instead we must use Integer—and add only Integers to this collection. AddAll error. We cannot pass an int array to the Collections.
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();
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