views:

435

answers:

6

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

+2  A: 

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++;
}
Gandalf
Best answer. Basically, you can't but there's no problem in creating your own counter.
Kibbee
If you want a counter, wouldn't you be better off just using a normal for loop?
ColinD
@ColinD - it's a toss up, but I find the foreach loops easier to read in general.
Gandalf
@downvote - care to explain? Show my another way WITH A FOREACH loop to keep track of the index, since that was the question.
Gandalf
+12  A: 

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

oxbow_lakes
In your second paragraph, I think you meant to write *index* not *syntax*.
Rob Sobers
The first for loop won't with a non-indexed Collection.
Steve Kuo
@Steve: yes ... but the question is asking about an array, not a Collection.
Stephen C
@Rob - cheers for the spot.
oxbow_lakes
+1  A: 

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.

Bart Kiers
+2  A: 

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
}
ColinD
+1  A: 

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
jitter
A: 

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();
}
TwentyMiles