I’ve been trying to figure out if there’s a simple way to extract the index of the iteration through a for-loop when using the for(elements in an array) style iteration.
It’s simple enough using the for(init; test; update) iteration:
for (int i = 0; i < limit; i++)
{
someArray[i]; // *just use i to get the item in that array index*
}
But if we look at the Bouncy Bubbles Example we iterate through the elements of the array of Balls:
Ball[] balls = new Ball[numBalls];
.
.
.
for (Ball ball : balls)
{
someArray[???]; // *how would we get the index the for-loop has iterated through here?*
ball.collide();
ball.move();
ball.display();
}
Of course, in the Bouncy Bubbles example, the Ball class has an int variable called id that gets indexed as it’s constructed, so we could do something like:
for (Ball ball : balls)
{
someArray[ball.id];
}
But what if you’re working with an array of objects that don’t have the id variable? Is there a way to get the iteration count from the for-loop? Or would it make more sense to switch to either an init/test/increment for loop, or implement an ID variable to the class’s objects?
The for-each loop that not provide a counter by itself, but you can provide your own counter.
The reason for this is that the for-each loop internally does not have a counter; it is based on the Iterable interface, i.e. it uses an Iterator to loop through the “collection” - which may not be a collection at all, and may in fact be something not at all based on indexes (such as a linked list).
So, the solution is to either have your own counter, like:
int index = 0;
for(Ball ball : balls) {
System.out.println("Current index is: " + (index++));
}
Yah. If the for-each-loop (enhanced for-loop) doesn’t have an internal counter and i have to introduce the iterator, I might as well just structure the for-loop to use the init-test-update model or introduce an ID variable to the class. Seems cleaner than introducing the iterator.
A lot of what i’m doing is sending values of FFT bands to instances of classes within arrays of that object. My current implementation is:
for (Ball ball : balls)
{
float fftVelocity = spectrum[ball.id] * 10.0 + 1; // THIS RIGHT HERE
ball.resize(fftDiameter[ball.id]);
ball.collide();
ball.move(fftVelocity);
ball.display();
}
Alternately, i’ll just structure it with an init/test/update for-loop in the future.
Was mostly curious if the enhanced for-loop has that internal counter. But you two gave me the info i needed. Thanks again! Cheers!
@GoToLoop Yah. For this example, the id variable is also used for other things within the class so it’s a handy identifier. And I was just having fun modifying Processing’s Bouncy Ball example. But in the future, yeah, if i need some sort of iterator i’ll just use the vanilla for ( ; ; ) loop. I usually do. Was mostly curious if there was some sort of counter within the enhanced for loop.