遍历ArrayList中的连续对象对 [英] Iterate over consecutive object pairs in an ArrayList
问题描述
我想从ArrayList中获取对象对,以便可以在每个对象的元素之间执行计算.理想情况下,它应该遍历成对的对象.例如,在具有{obj1,obj2,obj3,obj4}的列表中,它应该越过{obj1,obj2},{obj2,obj3}和{obj3,obj4}.
I want to get pairs of objects from an ArrayList so I can perform calculations between the elements of each object. Ideally it should iterate over pairs of objects. For example in a List with {obj1, obj2, obj3, obj4} it should go over {obj1,obj2}, {obj2,obj3} and {obj3,obj4}.
到目前为止,我尝试过的方法如下.
What I have tried so far is as follows.
public class Sum {
public ArrayList<Double> calculateSum(ArrayList<Iter> iter) {
ListIterator<Iter> it = iter.listIterator();
ArrayList<Double> sums = new ArrayList<>();
while (it.hasNext()) {
Iter it1 = it.next();
Iter it2;
if(it.hasNext()){
it2 = it.next();
} else { break; }
double sum = it1.getValue() + it2.getValue();
sums.add(sum);
}
return sums;
}
}
在这里,它只是迭代为{obj1,obj2}和{obj3,obj4}.我该如何解决?
Here, it just iterates as {obj1,obj2} and {obj3,obj4}. How can I fix this?
非常感谢所有帮助.谢谢!
All help is greatly appreciated. Thanks!
推荐答案
一个非常正常的循环,除了需要循环到list.size() - 1
, 在最后 之前. >数组的元素.
A very normal loop, except that you need to loop up to list.size() - 1
, the before last element of the array.
public ArrayList<Double> calculateSum(ArrayList<Iter> list) {
ArrayList<Double> sums = new ArrayList<>();
for (int i = 0; i < list.size() - 1; i++) {
double sum = list.get(i).getValue() + list.get(i + 1).getValue();
sums.add(sum);
}
return sums;
}
编辑
在这种情况下使用迭代器 不是 会比进行普通循环更快,并且只会使逻辑不必要地复杂并且容易引入错误.
Using an iterator in this case will not be faster than doing a normal loop and just makes the logic unnecessarily complicated and can easily introduce bugs.
这篇关于遍历ArrayList中的连续对象对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!