java Java迭代器在不增加的情况下获得下一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31080272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java iterator get next without incrementing
提问by Dzung Nguyen
I am writing the following loop in Java, for each loop I want to access the current and the next element of linked list r:
我正在用 Java 编写以下循环,对于每个循环,我想访问链表 r 的当前元素和下一个元素:
List<T> r = new LinkedList();
for (int i=0; i < r.size() - 1; i++) {
T current = r.get(i);
T next = r.get(i+1);
}
This might be wasting as everytime I call get(i), it start from the beginning so the run time order of the code is O(n^2). How do I achieve the same using Iterator (this time it will be O(n))? This is my first attempt:
这可能是浪费,因为每次我调用 get(i) 时,它都会从头开始,因此代码的运行时顺序是 O(n^2)。我如何使用迭代器实现相同的目标(这次是 O(n))?这是我的第一次尝试:
while(it.hasNext()) {
T current = it;
T next = it.next();
}
回答by rgettman
Maintain a variable previous
that is equal to the previous loop's current
value.
维护一个previous
等于前一个循环current
值的变量。
T previous = null;
// If it makes sense to skip the first "null, first element" pair...
if (it.hasNext())
{
previous = it.next();
}
while (it.hasNext())
{
T current = it.next();
// Process previous and current here.
// End of loop, after processing. Maintain previous reference.
previous = current;
}
This will be O(n) because you are using the Iterator
over your entire linked list.
这将是 O(n),因为您正在使用Iterator
整个链表。
回答by RealSkeptic
In each iteration, you should keep around a variable that will be the "current" and one that will be the "next". And you start processing your information starting from the seconditeration, when you already have a current
saved from the previous round.
在每次迭代中,您应该保留一个变量,即“当前”变量和“下一个”变量。然后您从第二次迭代开始处理您的信息,此时您已经current
保存了上一轮的信息。
T current = null;
T next = null;
Iterator<T> iter = r.iterator();
while ( iter.hasNext() ) {
next = iter.next();
if ( current != null ) { // Passed the first iteration
// Now you can use current and next, they both have values.
}
current = next; // Save what was the "next" as the next "current".
}
It's best to make sure that the list itself doesn't have null values. If it does, and it's a valid value, then you should have a boolean flag instead of just checking whether current != null
.
最好确保列表本身没有空值。如果是这样,并且它是一个有效值,那么您应该有一个布尔标志,而不仅仅是检查current != null
.
回答by FredK
T current = r.get(0);
for ( int i=0; i < r.size()-1; i++ ) {
T next = r.get(i+1);
// do stuiff here
current = next;
}