本文介绍了迭代 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 中的连续对象对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 02:04