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元素!
如果数据结构是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)
该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)
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)