2009-10-08 523 views
2

如何在foreach中引用數組的索引?參考Java的foreach中的迭代編號

我的代碼

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

我期待的是在foreach -loop將

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

我得到錯誤信息

的foreach並不適用於表達型

+2

你能提供更多的信息,爲什麼你認爲你需要一個索引?你真的在做一些與位置有關的事情嗎?或者你只是在對數組中的每個字符串做些什麼? – 2009-10-08 20:57:14

回答

15

這是因爲在使用foreach語法時索引不可用。你必須使用傳統迭代,如果你需要的指數:

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

如果不需要索引,標準foreach就足夠了:

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

編輯明顯你可以使用計數器得到索引,但是你有一個在循環範圍之外的變量,我認爲這是不受歡迎的

+0

在你的第二段中,我認爲你的意思是寫* index * not * syntax *。 – 2009-10-08 20:59:38

+0

第一個for循環將不包含非索引集合。 – 2009-10-08 21:02:12

+0

@Steve:是的......但問題是詢問一個數組,而不是一個集合。 – 2009-10-09 01:37:26

3

唯一的辦法就是跟蹤自己的櫃檯。

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

最佳答案。基本上,你不能但創建自己的計數器沒有問題。 – Kibbee 2009-10-08 20:36:31

+5

如果你想要一個計數器,難道你只是使用正常的循環更好嗎? – ColinD 2009-10-08 20:38:28

+0

@ColinD - 這是一個折騰,但我發現foreach循環更易於閱讀。 – Gandalf 2009-10-08 20:39:26

1

不,你不能這樣做。在增強的for語句中,只能遍歷Iterable。你不能在裏面做任何事情。

2

你的榜樣,foreach循環應該這樣來使用(複數names是名稱的數組比name一個更好的名字):

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

你並不需要一個計數器。只要做到

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

將輸出

hello 
world 
0

您使用每個循環不正確。它會自動給你一個你正在迭代的元素的引用,並且需要索引。正確的方法,在這種情況下,會是以下幾點:

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

如果您需要訪問一個可迭代對象的元素更多的靈活性,你可以直接使用迭代器。數組不提供迭代器,所以我在這裏使用List。

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