When I have a for loop, I use the i
to refer to the elements of my array, objects, etc.
Like:
Current item: myArray[i]
Next item: myArray[i+1]
Previous item: myArray[i-1]
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())
.
But when it returns true (so it finds what I look for), it should perform the code on the previous and the next item.
Clarification: I have java.awt.Component
elements!
If the data-structure is a List, then you can use a ListIterator directly. The ListIterator is special because it contains both the methods next()
and 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With