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;

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Please add an explanation of why this change is necessary.
@Arkanon: I was working on it. Does this new explanation make sense?
@dfriend21 because Integer is immutable and, on top of that, Java is pass by value, never by reference.
0

Your not assigning the value to anything you need to do

arrayListOfInteger.set(i, (arrayListOfIntegers.get(i) + 1));

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.