如果我要有一个包含五个元素0,1,2,3,4的java列表,它们都具有int数值。如何在我合并的元素的位置得到元素组合的总和
我使用的软件包如下:
java.util.ArrayList
java.util.LinkedList
java.util.Vector
java.util.Stack
java.util.iterator
实施例
myList(o) = 1
myList(1) = 2
myList(2) = 3
myList(3) = 4
myList(4) = 5
我合并元素1-3
myList(0) = 1
myList(1) = 9 //sum of elements 2,3,4, indexed as 1-3
myList(2) = 5
我要问的是,而不是自动将新值(在本例中为9)添加到列表的END到某个地方。
答案 0 :(得分:3)
只需重建列表并添加您的范围内的元素:
public static List<Integer> combine(List<Integer> list, int start, int end) {
ArrayList<Integer> lst2 = new ArrayList<>();
int sum = 0;
for (int i = 0; i < list.size(); i++) {
//If not in combine range, simply add the element to the new list
if (i < start || i > end) {
lst2.add(list.get(i));
} else {
//Otherwise, add element to combine sum, and add to list when we are done
sum += list.get(i);
if (i == end) {
lst2.add(sum);
}
}
}
return lst2;
}
从您的示例中,您似乎希望两端的范围包含。如果不是(并且结束索引应该是独占的),只需将i > end
更改为i >= end
,将i == end
更改为i == end - 1
。
答案 1 :(得分:0)
我相信你所寻找的是List.add(int index, Integer element)
超载。类似的东西:
public static void main(String[] args) throws Exception {
List<Integer> myList = new ArrayList() {{
add(1);
add(2);
add(3);
add(4);
add(5);
}};
sumSubList(myList, 1, 3);
System.out.println(myList);
}
public static void sumSubList(List<Integer> list, int start, int end) {
// Check to that start and end indices are within the bounds of the list
if ((start > end) ||
(start < 0) ||
(end > list.size() - 1))
return;
int sum = 0;
for (int i = start; i <= end; i++) {
sum += list.get(start);
// Remove this element after it's been added to the sum
list.remove(start);
}
// Add the sum at the starting point
list.add(start, sum);
}
结果:
[1, 9, 5]