10

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.

3
  • 3
    It is pretty ugly, but a lot of Java is. I'd consider wrapping it up in a method so your mainline code isn't cluttered. Commented Nov 29, 2014 at 18:04
  • 1
    I'm with @DaveNewton on this one. I can't see a better way but I'd wrap it up in a method for readability / testability. Commented Nov 29, 2014 at 18:07
  • int lastIndex = ints.size() -1; int lastValue = ints.get(lastIndex); ints.set(lastIndex, lastValue + 1); Commented Nov 29, 2014 at 18:08

5 Answers 5

19

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

Sign up to request clarification or add additional context in comments.

Comments

13

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();

4 Comments

Even though AtomicInteger does not have autoboxing. Using linkedList and atomic integer makes the code much more cleaner
But coding isn't just about aesthetics. Why use Atomic* is there's no concurrency thing involved. It's unnecessary overhead. Different datastructure usage should be based on use-case Not on looks.
When you work on a small project - I will agree with you. When you have a team of 400-500 developers... readability and supportability becomes the most important thing. It would be a necessity to use standard structures, even if this means "overhead".
In that case you'd better create your own class wrapping an int that has increment(). As opposed to have that overhead of AtomicInteger
2

I have done something like this:

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

here is an example from my code (modified 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.

Comments

0

I can done by the code using java ...In that we can Increment each element of the list

List<Integer> list= new ArrayList<Integer>();
  //int[] primitive = List1.toArray(list1);
  int count=0;
  int count1=0;
  int k=0;
  list.add(3);list.add(2);list.add(3);list.add(5);
  System.out.println("The given input is");
  for(int i:list){
      System.out.println(i);
  }
  Integer[] a = list.toArray(new Integer[list.size()]);
  for(int i = 0; i <a.length; i++)
    {
        if(i==a.length-1){
            a[i]++;
            count++;
        }else if(i==a.length-2){
            a[i]++;
            count++;
        }else if(i==a.length-3){
            a[i]++;
            count++;
        }else if(i==a.length-4){
            a[i]++;
            count++;
        }

    }
  System.out.println("After first operation");
  for(int i:a){
      System.out.println(i);
  }

  System.out.println("the first count is"+count);
  for(int i = 0; i <a.length; i++)
    {
        if(i==a.length-1){
            a[i]--;
            count1++;
        }else if(i==a.length-2){
            a[i]--;
            count1++;
        }else if(i==a.length-3){
            a[i]--;
            count1++;
        }else if(i==a.length-4){
            a[i]--;
            count1++;
        }

    }

   for(int i:a){
      System.out.println(i);
  }
   System.out.println("the second count is"+count1);
  //int Count2=count+count1;
   System.out.println("After second operation");



  System.out.println("--------------------------------------------");
  for(int j:a){
      System.out.println(j);
  }
 List<Integer> list1=Arrays.asList(a);

  System.out.println("After conversion of list");
  for(int i:list1){
      System.out.println(i);
  }

i made the count also...

This question asked in one of the interview also..

Comments

0
  1. You may always use plain arrays:
int[] ints = new int[10];

++ints[9];
// or
++ints[ints.length - 1];

Note: however, usually, it is safer to stick to the List.

  1. If you have a lot of incrementing, you can write a small neat code snippet:
private static void increment(List<Integer> list, int ind) {
    list.set(ind, list.get(ind) + 1);
}
List<Integer> list = new ArrayList<>();
list.add(5);
list.add(15);

increment(list, list.size() - 1);

Note: even if you need to increment only one time in one function, it may be worth it to have such a snippet for readability.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.