Reputation: 29
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);
}
Upvotes: 1
Views: 462
Reputation: 365
This is the best solution for a foreach-loop. Otherwise you could use something like:
for (int i = 0; i<levelBtns.lenght; i++) {
levelBtns[i] = new Button(160, (i + 40) * 50, 100, 40);
}
Upvotes: 1
Reputation: 892
If it's not an Iterable, but a Collection or array, you're iterating through, and you need the number of iterations after the loop, just use Collection.size() method or length field of an array to get the size of it, which is also the number of iterations.
Upvotes: 1
Reputation: 121998
Your solution is ok and it's general. But a possible way is
You can get the counter value by getting , If it is a List then levelBtns.size()
of if an array then array.length
Upvotes: 0