简体   繁体   中英

How do I find the number of times I've iterated through a foreach loop?

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

如果不是Iterable,而是Collection或数组,则要进行迭代,并且需要循环后的迭代次数,只需使用Collection.size()方法或数组的length字段来获取它的大小,这也是迭代次数。

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM