Link to iteration number in Java foreach

How can you reference an array index in foreach?

My code

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

I expect foreach -loop to be

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

I get an error

foreach is not an expression type

+3
source share
6 answers

This is because the index is not accessible using syntax foreach. You should use traditional iteration if you need an index:

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

If you do not need an index, a standard one foreachwill be enough:

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 find undesirable

+16
source

.

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

foreach ( names , name):

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

, . for-statement Iterable. .

+1

.

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

hello
world
+1

. , , . :

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

If you need more flexibility when accessing elements of an iterable object, you can use an iterator directly. Arrays do not provide iterators, so I use 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();
}
0
source

Source: https://habr.com/ru/post/1719662/


All Articles