Java - 如何在迭代期间引用上一个和下一个元素?

Apa*_*che 7 java foreach loops

当我有一个for循环时,我用它i来引用我的数组,对象等的元素.

喜欢:
当前项目:myArray[i]
下一项:myArray[i+1]
上一项:myArray[i-1]

但此刻,我正在使用foreach循环(for (Object elem : col) {).
我如何参考上一个项目?
(我需要搜索一个'数组',我正在做的for (Object object : getComponents()).

但是当它返回true时(所以它找到了我想要的东西),它应该在前一个下一个项目上执行代码.

澄清:我有java.awt.Component元素!

Sur*_*ran 9

如果数据结构是List,则可以直接使用ListIterator.ListIterator是特殊的,因为它包含方法next()previous()

List list = ...;
ListIterator iter = list.listIterator(); //--only objects of type List has this
while(iter.hasNext()){
    next = iter.next();
    if (iter.hasPrevious()) //--note the usage of hasPrevious() method
       prev = iter.previous(); //--note the usage of previous() method
}
Run Code Online (Sandbox Code Playgroud)

  • 当然,应该注意的是 `previous()` 将迭代器 _backwards_ 移动,这意味着对 'next()` 和 'previous()` 的成对调用将导致迭代器保持原位的净效果。 (2认同)
  • @Suraj - 你没有提到`previous()`总是移动迭代器****(虽然因为`next()`而可能是可以推断的).所有`hasPrevious()`都可以防止异常被抛出 - 你需要另外调用`next()`来实现循环才能实现... (2认同)

Jac*_*nds 5

foreach循环不会让你做到这一点.我的建议是回到使用老式的老式Iterator.例如

final Iterator itr=getComponents().iterator();
Object previous=itr.next();
Object current=itr.next();
while(itr.hasNext()){
    Object next=itr.next();
    //Do something with previous, current, and next.
    previous=current;
    current=next;
}
Run Code Online (Sandbox Code Playgroud)


Ser*_*nev 3

JButton prev, next, curr;
Component[] arr = getComponents();

for(int i=1;i<arr.length-1;i++) {
    if (yourcondition == true) {
        curr = (JButton) arr[i];
        prev = (JButton) arr[i-1];
        next = (JButton) arr[i+1];
    }
}
Run Code Online (Sandbox Code Playgroud)