Reputation: 882
Why doesn't this work?
private List<Integer> xShot = new ArrayList<Integer>();
...codes
...codes
...codes
...codes
xShot.get(0) += 5;
Can't understand why the left-hand side of an assignment´isn't is a variable..
Someone help?
Upvotes: 3
Views: 14824
Reputation: 20961
If you just want to increment by 5 and aren't limited to List<Integer>
specifically, you could avoid arguably verbose xShot.set(0, xShot.get(0) + 5)
and do this instead:
List<AtomicInteger> xShot = new ArrayList<AtomicInteger>();
xShot.get(0).addAndGet(5);
This will increment the value of the AtomicInteger
in xShot.get(0)
by 5 in-place without further ado.
Upvotes: 0
Reputation: 68887
It is like saying in Java:
5 = 6; // "Assign 5 to 6"
The left side (5
) isn't variable.
Why is this example statement relevant? Because of Java uses always "pass by value". Which means that the return value of a method is also "return by value".
This is pure mathematical: you can't change a value, you can change a variable. The same for Java. Five can never become six.
In other words: Only a value can be assigned to a variable.
So, the correct way of doing what you want is:
xShot.set(0, xShot.get(0) + 5);
Edit: In your situation: xShot.get(int)
doesn't return a variable, but a value.
Upvotes: 1
Reputation: 128899
xShot.get(0)
is a method call that returns a value. A variable is something you declare with a type that holds a value, like int x;
, String name;
, or List<Integer> xShot
from your example. Those are the only things in Java that you can assign a value to using an assignment operator.
Upvotes: 5
Reputation: 425208
xShot.get(0)
returns an object; it isn't a variable, so you can't assign to it.
Also, Integer
is immutable (you can't change its value), so you would have to replace the object at position 0
with a new Integer
that has the calculated value.
You can achieve the intention of that line like this:
xShot.set(0, xShot.get(0) + 5);
Upvotes: 2
Reputation: 5452
Although xShot.get(0) is a number, it is not a variable. You need to provide a variable for this to work. That said
int i = xShot.get(0);
i += 5;
Will not work. i
will be incremented by 5, but xShot's object in location 5 is not the same object. You need to get, modify, and set the variable.
For example:
xShot.set(0, xShot.get(0) + 5);
Upvotes: 5
Reputation: 7523
The left-hand side of the assignment has to be explicitly a variable because in your case of statement , the expression could be a constant also , which would be a error if allowed
Upvotes: 0