0

I have an already existing ArrayList<Integer> and I'd like to add 1 to an Integer at a specific index. However, it gives me the error that "The left-hand side of an assignment must be a variable." It's something like this:

arrayListOfIntegers.get(i) += 1;
dfriend21
  • 89
  • 7

2 Answers2

10

The += operation is supposed to act on a variable--a local variable, a field, etc. And Integers are immutable, so you can't really change their value directly--5 will always be 5, and if you add 1 to it, you end up with a new number (6).

So you need to first "get" the value that is at the given index, and then "set" the value at that index to the new number that comes from adding one to the original value:

arrayListOfIntegers.set(i, arrayListOfIntegers.get(i) + 1);
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
0

Your not assigning the value to anything you need to do

arrayListOfInteger.set(i, (arrayListOfIntegers.get(i) + 1));
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
brso05
  • 13,142
  • 2
  • 21
  • 40