Lui*_*uis 10 java iterator copy
我们有一个元素列表,并且有一个非常简单的碰撞检测,我们检查每个对象与其他所有对象.
检查是可交换的,所以为了避免重复两次,我们将在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);
}
}
Run Code Online (Sandbox Code Playgroud)
这里的关键是副本
it1 = it0
Run Code Online (Sandbox Code Playgroud)
你会怎么用Java写这个?
您无法复制Java迭代器,因此您必须在没有它们的情况下执行此操作:
for(int i=0; i<list.size(); i++){
for(int j=i; j<list.size(); j++){
Test(list.get(i), list.get(j));
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用ListIterator执行此操作:
for(ListIterator<O> outer = list.listIterator(); outer.hasNext() ; ) {
O oVal = outer.next();
for(ListIterator<O> inner = list.listIterator(outer.nextIndex()); inner.hasNext(); ) {
Test(oVal, inner.next());
}
}
Run Code Online (Sandbox Code Playgroud)
对于链接列表(索引访问速度较慢),list.listIterator(index)
仍然需要迭代到正确的位置.但是这样只有O(n²)(并且你不能比这更好)而不是像其他答案中的索引访问那样的O(n³).(如果先将列表复制到数组中,可能会更快,但这只是一个常数因素.)
当然,如果您通常需要基于索引的访问(或此迭代器克隆),则最好使用基于数组的列表(或迭代器支持克隆的自定义列表).