4

I have read that

    for (int i1 : A) {
    }

is better than

    for (int i1=0; i1 < A.length; i++) {
    }

but if I want to access index value in first one is there any mean or should I use the second one only.

7 Answers7

3

Wikipedia states:

foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one errors and makes code simpler to read.

If you want to use index, it's better to use latter version.

if I want to access index value in first one is there any mean

Yes, you can

int index = 0;
for (int i1 : A) 
{
    // Your logic
    // index++;
}

but again, not recommended. if you need index in Enahanced for loop, rethink your logic.

Java recommends the enahanced for loop: Source (See last line on page)

Azodious
  • 13,752
  • 1
  • 36
  • 71
0

No, there isn't. You just would have to declare a variable. Better just use the traditional one in that case.

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
0

Use this or Best to go with Second option

  int count = 0;
 for (int i1 : A) {
    print count;
    count ++;
    }
sunleo
  • 10,589
  • 35
  • 116
  • 196
0

No way as mentioned above, have a look also at this similar question Is there a way to access an iteration-counter in Java's for-each loop?

Community
  • 1
  • 1
Wayne Earnshaw
  • 527
  • 6
  • 15
0

you have to use the second one. Your other option is to use a collection List as
List list = Arrays.asList(int a[]); list.get(int index);

clinton
  • 612
  • 3
  • 6
0

You first code says, go through all items/object in the collection A, But the last code says to go to through the index from 0 to n, n=>size of A

In the normal case both will work, and what to select is normally based on which API for loop through you can use.

In you first code works on a HashMap or not fill Array. Say you have this data structure

A = [1,2,3,NULL,NULL,4,NULL,5]

In your first case it is possible to only loop through the existing values. But in the last case you must loop through all elements.

Also an unordered or well defined data structure like Maps can have a method that guarantees you go through all elements but not in a well defined order.

Junuxx
  • 14,011
  • 5
  • 41
  • 71
FIG-GHD742
  • 2,486
  • 1
  • 19
  • 27
0

No you cant. The for-each is considered better (to quote your question) because it does not have the count variable. This means there are fewer places to go wrong from a programmer point of view. It is not up to you the programmer to retrieve the data. Java does it for you with the for each.

I tend to use for-each whenever I do not need the counter variable. If I need the count then I have to use the old style for loop.

RNJ
  • 15,272
  • 18
  • 86
  • 131