Java 将 ArrayList 中的所有整数元素加 1
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19199171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Increment all integer elements by 1 in a ArrayList
提问by Sravan2023
I need to increment the values for certain part of a ArrayList by a given number.
我需要按给定数字增加 ArrayList 某些部分的值。
like [ 1 2 3 4 5 6 7 8 9 1 1 1 ]
lets say i need to increment last 3 elements by 2
so that the result would be
像[ 1 2 3 4 5 6 7 8 9 1 1 1 ]
可以说,我需要通过2递增最后3个元素,这样的结果将是
[ 1 2 3 4 5 6 7 8 9 3 3 3 ]
how can i do this ?
我怎样才能做到这一点 ?
采纳答案by Erik Kaplun
Assuming arrayList
contains the ArrayList<Integer>
instance:
假设arrayList
包含ArrayList<Integer>
实例:
int startFrom = arrayList.size() - 3;
int upTo = arrayList.size();
int incrBy = 2;
for (int i = startFrom; i < upTo && i < arrayList.size(); i += 1) {
int oldValue = arrayList.get(i);
int newValue = oldValue + incrBy;
arrayList.set(i, newValue);
}
or, more compactly (i.e. inlining the variables oldValue
and newValue
):
或者,更简洁(即内联变量oldValue
和newValue
):
for (int i = startFrom; i < upTo && i < arrayList.size(); i += 1) {
arrayList.set(i, arrayList.get(i) + incrBy);
}
回答by Ravi Thapliyal
Hint :ArrayList
provides indexed access to its members. You can easily loop over the required elements. For incrementing last n
elements make use of a for
loop and list's size()
.
提示:ArrayList
提供对其成员的索引访问。您可以轻松地遍历所需的元素。为了增加最后一个n
元素,请使用for
循环和列表的size()
.
回答by MaD
Assuming that the part that needed to be incremented in known [from, to]. You just loop on the ArrayList and add the number you wish: (remember that you can access the items in the ArrayList by index)
假设需要在已知[from, to] 中递增的部分。您只需在 ArrayList 上循环并添加您想要的数字:(请记住,您可以通过索引访问 ArrayList 中的项目)
arr - is ArrayList
arr - is ArrayList
number- is the number you wish to increment by
number- 是您希望增加的数字
for (int i = from; i < to; i++){
int item = arr.get(i);
arr.set(i,item+number);
}
- I assume here that
from
andto
are valid indexes for the ArrayList but you should always check if they are within the array bounds
- 我这里假设
from
和to
是ArrayList的有效指标,但您应经常检查,如果他们是在阵列范围内