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!
Array indexing
If you have an array-like data-structure (e.g. an actual array or something like an
ArrayList
), then referencingi
,i-1
,i+1
will give good performance so there isn't much more to it. (Although having to turn a For-Each Loop into an index counting For Loop isn't very fun and is one of the few caveats.)The answer offered by Sergey does something like this.
The versatile
ListIterator
If you can get your hands on an
ListIterator
(which is actually quite a big assumption), the answer offered by Suraj could suffice. But do note bothnext()
andprevious()
moves the iterator position. So if you did something like the following for each loop iteration:prev = previous(); current = next(); next = next(); previous()
, you'll end up performing roughly 4 iteration operations per loop. This isn't much of a problem if iteration is cheap, and luckily this is often the case for data-structures that offers aListIterator
.Generic solution
The generic solution for any
Iterable
(orIterator
) should make no random lookups (as is possible with an array) or make assumptions regarding performance ofnext()
, which should be called at most N times where N is the number of available elements.Here's one such implementations:
Mind, this implementation has caveats of its own:
Iterable
containsnull
elements.current
ornext
are effectively-final, so cannot be used directly in them fangled Java 8 lambdas.The
foreach
loop won't let you do that. My suggestion is to go back to using the good old fashionedIterator
. For exampleIf 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()