-5

This is perhaps a random and nitpicky question, but I've been doing a lot of work with array manipulation in Java recently, and I was wondering whether, when using the following loop:

for (Object obj : SomeArrayOrCollection) {
    //do something
}

if there's any way to access some kind of ordinal without doing what I usually do (declaring an extra variable and adding one to it every time the loop runs) or what one of my coworkers does (using the

List.indexOf(int i) 

method)? I feel like both of these add rather a lot of overhead. I know that I could just use a standard

for (declaration;condition;change) { }

loop, but it's significantly more convenient in the context of this project to use the modified for loop. So, the question is, is there any way to access the index of the object you're working with without resorting to a more memory-intensive operation like I have above?

Thanks!

nameless912
  • 367
  • 1
  • 12

5 Answers5

3

No, for-each loops do not keep track of what index they are on because not every Iterable is indexable. Most Sets, for example, have no concept of order, so it makes no sense to say "the loop is on the element with the nth index". If you want to keep track of what iteration the loop is on, then you will need to use a counter as you suggested.

arshajii
  • 127,459
  • 24
  • 238
  • 287
1

If you want to aceess index then you can use

for (int i=0;i<SomeArrayOrCollection.length;i++) {
    //Here i is the index
}

By using for each you can not access the index

The reason is that the for-each loop internally does not have a counter; it is based on the Iterable interface.

SEE HERE

Community
  • 1
  • 1
PSR
  • 39,804
  • 41
  • 111
  • 151
1

Modified for loop was created for easily accessing collections like ArrayLists. You cannot acess the index by default in enhanced for loop. If you want to do that, you will have to either use conventional for loop i.e. for(initialization; condition ; change ) or you can declare a variable outside for loop and increment it inside

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
0

No, there isn't. Could you explain why the standard for loop is so unconvenient if you need the index?

herman
  • 11,740
  • 5
  • 47
  • 58
0

Actually, no, I think what you usually do is the right thing to do. Using indexOf is definitely wrong unless the list implementation is backed by a hash map (which I would not expect).

avidD
  • 441
  • 1
  • 6
  • 16