[英]The left-hand side of an assignment must be a variable
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?有人帮忙吗?
xShot.get(0)
is a method call that returns a value. xShot.get(0)
是一个返回值的方法调用。 A variable is something you declare with a type that holds a value, like int x;
变量是您声明的类型,它具有一个值,例如int x;
, String name;
, String name;
, or List<Integer> xShot
from your example. ,或您示例中的List<Integer> xShot
。 Those are the only things in Java that you can assign a value to using an assignment operator . 这些是Java中唯一可以使用赋值运算符赋值的东西 。
Although xShot.get(0) is a number, it is not a variable. 尽管xShot.get(0)是数字,但它不是变量。 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. i
将增加5,但是xShot在位置5的对象不是同一对象。 You need to get, modify, and set the variable. 您需要获取,修改和设置变量。
For example: 例如:
xShot.set(0, xShot.get(0) + 5);
xShot.get(0)
returns an object; xShot.get(0)
返回一个对象; 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. 另外, Integer
是不可变的(您无法更改其值),因此您将必须使用具有计算值的新 Integer
替换位置0
处的对象。
You can achieve the intention of that line like this: 您可以这样实现该行的目的:
xShot.set(0, xShot.get(0) + 5);
It is like saying in Java: 就像在Java中说的那样:
5 = 6; // "Assign 5 to 6"
The left side ( 5
) isn't variable. 左侧( 5
)不变。
Why is this example statement relevant? 为什么此示例语句相关? Because of Java uses always "pass by value". 因为Java 总是使用“按值传递”。 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. 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. 编辑:在您的情况下: xShot.get(int)
不返回变量,而是一个值。
赋值的左侧必须明确地是一个变量,因为在您的statement情况下,表达式也可以是常量,如果允许的话将是错误的
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: 如果您只想增加5,而不仅限于List<Integer>
,则可以避免冗长的xShot.set(0, xShot.get(0) + 5)
来代替:
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. 这将xShot.get(0)
AtomicInteger
的值增加5。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.