Best way to increment Integer in arrayList in Java

What is the cleanest way to increment Integer in an ArrayList?

ArrayList<Integer> ints = new ArrayList<>(); ints.add(5); ints.add(9); 

What is the cleanest way to increase the last item?

ints.set(ints.size() - 1, ints.get(ints.size() - 1) + 1); seems to me pretty ugly.

+6
source share
3 answers

Perhaps you need to use a different data structure?

 LinkedList<AtomicInteger> list = new LinkedList<AtomicInteger>(); ints.add(new AtomicInteger(5)); ints.add(new AtomicInteger(9)); list.getLast().incrementAndGet(); 
+6
source

You cannot increase the value because Integer objects are immutable. You will need to get the previous value at a specific position in the ArrayList , increase the value and use it to replace the old value at the 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 variable integer type, such as AtomicInteger (or write your own).

+10
source

I did something like this:

 arraylistofint.set(index, arraylistofint.get(index) + 1); 

here is an example from my code (changed names):

 ArrayList<Integer> numBsPerA = new ArrayList<> (); ... int cntAs = 0; int cntBs = 0; for ( TypeA a : AnArrayListOfAs ) { numBsPerA.add(0); for ( TypeB b : a.getAnArrayListOfBs() ) { numBsPerA.set(cntAs, numBsPerA.get(cntAs) + 1); cntBs++; } System.out.println(a.toString()+ " has " +numBsPerA.get(cntAs)+" TypeBs"); cntAs++; } System.out.println("Total number of As: "+cntAs); System.out.println("Total number of Bs: "+cntBs); // can now loop over numBsPerA to check how many Bs per A or whatever. 
+1
source

Source: https://habr.com/ru/post/978873/


All Articles