1

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);
}
5
  • Do you need the information in the loop or after the loop? Commented Jan 5, 2014 at 17:37
  • I believe you have already posted the best solution. However, if you are concerned about what iteration your currently on, why not switch to a traditional for loop. Commented Jan 5, 2014 at 17:37
  • The solution is completely fine. Commented Jan 5, 2014 at 17:37
  • I am assuming levelBtns is an array or a Collection of some sort, therefore the number of iterations would be lvlButtons.length or lvlButtons.size() ? Commented Jan 5, 2014 at 17:39
  • 4
    Your code is currently pointless anyway, as you're assigning a new value to the iteration variable... which does nothing useful. Commented Jan 5, 2014 at 17:39

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);
}

1 Comment

OP already mentioned I know I could just use a normal for loop and have an iterator, But I believe this is the clean solution.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.