迭代conseecutive对象对在一个ArrayList [英] Iterate over conseecutive object pairs in an ArrayList

查看:158
本文介绍了迭代conseecutive对象对在一个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?

所有帮助是极大的AP preciated。谢谢!

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.

这篇关于迭代conseecutive对象对在一个ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆