Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to increment Integer in arrayList in Java

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.

like image 276
WVrock Avatar asked Nov 29 '14 18:11

WVrock


People also ask

Which method is used to increase capacity of ArrayList?

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.

How can an ArrayList improve performance?

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.

Can you add int to Integer ArrayList Java?

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.


2 Answers

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).

like image 184
Sotirios Delimanolis Avatar answered Sep 19 '22 06:09

Sotirios Delimanolis


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();
like image 24
ursa Avatar answered Sep 20 '22 06:09

ursa