Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How do I refer to the previous and next element during an iteration?

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!

like image 669
Apache Avatar asked Dec 19 '11 17:12

Apache


1 Answers

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
}
like image 110
Suraj Chandran Avatar answered Sep 19 '22 13:09

Suraj Chandran