Java-如何在迭代过程中引用上一个和下一个元素? [英] Java - How do I refer to the previous and next element during an iteration?

查看:102
本文介绍了Java-如何在迭代过程中引用上一个和下一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I have a for loop, I use the i to refer to the elements of my array, objects, etc.

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

Like:
Current item: myArray[i]
Next item: myArray[i+1]
Previous item: myArray[i-1]

但是目前,我正在使用 foreach 循环(for (Object elem : col) {).
如何参考上一项?
(我需要搜索与for (Object object : getComponents())相同的数组".

But at the moment, I'm using a foreach loop ( for (Object elem : col) { ).
How do I refer to the previous item?
(I need to do a search an 'array', which I'm doing with for (Object object : getComponents()).

但是当它返回true(以便找到我想要的东西)时,它应该在 previous next 项目上执行代码.

But when it returns true (so it finds what I look for), it should perform the code on the previous and the next item.

说明:我有java.awt.Component个元素!

推荐答案

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];
    }
}

这篇关于Java-如何在迭代过程中引用上一个和下一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆