0

I have a following for loop

ArrayList<User> userList;
for(User user:userList){
    ....
}

How do I get the index of the current obj that im working with? I could change it regular for(int i...) loop but this would be counter productive.

Thanks.

4

5 回答 5

3

It makes perfect sense to use for(int i...) if you want to use the index.

于 2013-04-17T11:26:53.833 回答
3

You have to use your own counter like this one

int counter = 0;
ArrayList<User> userList;
for(User user:userList){
    ....

counter++;
}

This is because java for each loop is based on iterator which is not based on index based iteration. Actually foreach loop internally uses an iterator. so it doesn't have any index. It moves automatically over the items of a collection or list, grabbing a reference to each one as you need it.

See this image

enter image description here

In this way iterator traverse each element or object without indexes. So as the for loop.

or you can use

User user = null;

for (int counter = 0; counter < userList.size(); counter++) {
   user  = userList.get(counter);
}
于 2013-04-17T11:29:20.907 回答
2

You could use a separate counter:

int index = 0;
for (User user: list) {
    //use index
    index++;
}

But to be honest, if you do need the index, it is probably easier to just use a plain old for loop:

for (int i = 0; i < list.size(); i++) {
    User user = list.get(i);
}
于 2013-04-17T11:27:16.373 回答
2

This type of looping is called foreach loop.. it iterate on collection elements so there is no really index.. it's like vector which have iterator (if you know stl in c++)

The regular for loop as you said (for (int i = 0 ... ) ) will give the index as you want

于 2013-04-17T11:29:42.797 回答
1

I'm afraid you'll have to go with this or the for loop with the counter. There is no other way.

int index = 0;
for(User user:userList){
    ....
    index++;
}
于 2013-04-17T11:27:18.223 回答