Reference to the iteration number in Java's foreach

How can you refer to the index of an array in the foreach?

My code

String[] name = { "hello", "world" };
for ( int k : name[k] ) {
   --- cut ---
}

I expecting that the foreach -loop will

1. set k = 0 in first iteration so that name[0] works correctly
2. set k = 1 in the next iteration...

I get the error message

foreach not applicable to expression type

Upvotes: 4

Views: 13880

Answers (8)

Joy
Joy

Reputation: 21

As there is problem with index accuracy converting array to list when array consists of duplicates. For the timing, recommending this solution on top of using enhanced for-loop for list.

    String[] tokens = new String[] { "I", "Love", "You", "You" };
    for(int i=0; i<tokens.length; i++) {
        System.out.println("token at index "+i+" is: "+tokens[i]);
    }

Upvotes: 0

Joy
Joy

Reputation: 21

    Integer index = null;
    String[] tokens = new String[] { "I", "Love", "You" };
    List<String> arrs = Arrays.asList(tokens);
    for (String arr : arrs) {
        index = arrs.indexOf(arr);
        System.out.println("Index of " + arr + " is: " + index);
    }

Upvotes: 2

oxbow_lakes
oxbow_lakes

Reputation: 134270

That's because the index is not available when using the foreach syntax. You have to use traditional iteration if you need the index:

for (int i =0; i < names.length; i++) {
   String name = names[i];
}

If you do not need the index, the standard foreach will suffice:

for (String name : names) {
    //...
} 

EDIT: obviously you can get the index using a counter, but then you have a variable available outside the scope of the loop, which I think is undesirable

Upvotes: 18

TwentyMiles
TwentyMiles

Reputation: 4089

Your using the for each loop incorrectly. It automatically gives you a reference to each element in what you are iterating over, and there is to need to index. The correct way, in this case, would be the following:

String[] name = {"hello", "world"};
for(String s : name){
    System.out.println(s);
}

If you need more flexibility in accessing the elements of an iterable object, you can use the iterator directly. Arrays don't provide iterators, so I've use a List here.

List<String> name = Arrays.asList(new String[]{"hello", "world"});

for(Iterator<String> it = name.iterator(); it.hasNext();){
    String currentName = it.next();
    System.out.println(currentName);
    it.remove();
}

Upvotes: -2

jitter
jitter

Reputation: 54605

You don't need an counter. Just do

String[] name = { "hello", "world" };
for ( String s : name ) {
   --- cut ---
   System.out.println(s);
   --- cut ---
}

Which will output

hello
world

Upvotes: 0

ColinD
ColinD

Reputation: 110054

With your example, the foreach loop should be used like this (the plural names is a better name for an array of names than name):

String[] names = { "hello", "world" };
for ( String name : names ) {
   // do something with the name
}

Upvotes: 1

Bart Kiers
Bart Kiers

Reputation: 170158

No, you can't do that. Inside an enhanced for-statement, you can only iterate over an Iterable. You can't do anything else inside it.

Upvotes: 2

Gandalf
Gandalf

Reputation: 9855

Only way would be to keep track yourself with a counter.

int cnt = 0;
String[] names = new String[10];
for (String s : names) {
   ...do something...
   cnt++;
}

Upvotes: 3

Related Questions