1

Overview:

I'm using for-each loops and I'm curious if I need to replace them with regular for loops, or if there is a way to do a locate in an ArrayList which will give me the equivalent of keeping track of the index which is used in normal for loops.

Simplified Version of the Problem:

I'm using for-each with an ArrayList of objects. These objects are used to calculate different values at different times, so I need to iterate through the items and do the calculates a couple different times. I wish to track these results in a structure, which I can easily do, if I can locate items in an ArrayList (without having to iterate through everything in a separate loop). If there is, then I can use that to build what I need. If not, I'll replace the for-each with for loops and get the functionality I need.

dimo414
  • 42,340
  • 17
  • 131
  • 218
James Oravec
  • 16,761
  • 25
  • 77
  • 145
  • 1
    Locate them how? `indexOf()`? – Sotirios Delimanolis Jun 03 '14 at 15:13
  • For complex objects, to locate an element in a `List`, based on a particular member, you can override the `equals` method in the parameterized class to match with the specific thing (an id member for example). Then, `yourList.contains(new YourClass(4));`. It's not applicable with all cases but should be usefull. – lpratlong Jun 03 '14 at 15:14
  • @SotiriosDelimanolis, that is exactly what I needed, thanks. – James Oravec Jun 03 '14 at 15:15
  • @VenomFangs I don't know what you want to do but indexOf can be a fairly expensive operation depending on the size of the list and the type of objects in the list. – assylias Jun 03 '14 at 15:16
  • @VenomFangs You have `lastIndexOf` also, if you need to get the last occurrence of an element. – lpratlong Jun 03 '14 at 15:17
  • Arshajii's answer gives me what I need without the expensive operations :) Thx. – James Oravec Jun 03 '14 at 15:18

2 Answers2

2

The for-each loop is meant to be an easy way to operate on every element in a collection or array. If you want to iterate and keep track of indicies, you'll want a normal for loop.

However, some Collections (Lists for example) have an indexOf() method which you can use to get the index. That would kill your performance though.

You can also use a counter:

int i = 0;
for (Object o : list) {
    // Code
    i++;
}
Anubian Noob
  • 12,897
  • 5
  • 47
  • 69
2

You can use a regular for-loop but sometimes it just isn't a good idea, for example if you're dealing with linked lists where element retrieval is O(n) in the index. Why not just keep track of index?

int index = 0;
for (Element e : list) {
    ...
    index++;
}

I find this cleaner than a plain for-loop, and it will remain efficient even if you change from ArrayList to another type of list which is not random-access.

arshajii
  • 118,519
  • 22
  • 219
  • 270