如何在 Java 中制作迭代器的副本?

2022-01-20 00:00:00 复制 iterator java

我们有一个元素列表,并且有一个非常简单的碰撞检测,我们检查每个对象与其他对象.

We have a list of elements and have a very simplistic collision detection where we check every object against every other object.

检查是可交换的,所以为了避免重复两次,我们会在 C++ 中这样做:

The check is commutative, so to avoid repeating it twice, we would do this in C++:

for (list<Object>::iterator it0 = list.begin(); it0 != list.end(); ++it0)
{
    for (list<Object>::iterator it1 = it0; it1 != list.end(); ++it1)
    {
        Test(*it0, *it1);
    }
}

这里的关键是副本

it1 = it0

你会如何用 Java 写这个?

How would you write this in Java?

推荐答案

你不能复制 Java 迭代器,所以你必须在没有它们的情况下这样做:

You cannot copy Java iterators, so you'll have to do it without them:

for(int i=0; i<list.size(); i++){
    for(int j=i; j<list.size(); j++){
        Test(list.get(i), list.get(j));
    }
}

相关文章