If I'm trying to find the number of times I've iterated through a foreach loop in java is there a better way to do it than this?
int i = 0;
for (Button button : levelBtns) {
button = new Button(160, 40 + (i * 50), 100, 40);
i++;
}
I know I could just use a normal for loop and have an iterator, i, but I was just wondering if there was a more elegant way to do this with a foreach.Thanks in advance :)
EDIT: As Jon Skeet pointed out, the code above assigns the new button instance to the iteration variable. Oops. Based on other comments, I believe the most practical thing to use is a normal loop. Here's the version I'm going with. Thanks everyone for your help!
Button[] levelBtns = new Button[6];
for (int i = 0; i < levelBtns.length; i++) {
levelBtns[i] = new Button(160, 40 + (i * 50), 100, 40);
}
levelBtns
is an array or aCollection
of some sort, therefore the number of iterations would belvlButtons.length
orlvlButtons.size()
?