简体   繁体   English

添加到已经存在于ArrayList中的Integer中

[英]Adding to an Integer already in an ArrayList

I have an already existing ArrayList<Integer> and I'd like to add 1 to an Integer at a specific index. 我已经有一个ArrayList<Integer> ,我想在特定索引处将1添加到Integer中。 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;

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). +=操作应该作用于变量-局部变量,字段等。并且整数是不可变的,因此您不能真正直接更改其值--5始终为5,如果加上1最终得到一个新数字(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: 因此,您需要首先“获取”给定索引处的值,然后“将该”索引处的值“设置”为新数字,该新数字是将原始值加1的结果:

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

您没有将价值分配给您需要做的任何事情

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM