2011-01-10 27 views

回答

1
foreach(object o in arrayList) 
{ 
// cast to appropriate type 
// eg string s = o as string; 
// ... 
} 
+0

這不是Java代碼。 – 2011-01-10 06:19:47

3

這是一個使用「for-each循環」遍歷ArrayList中的String元素的示例。

ArrayList<String> list = new ArrayList<String>(); 
    ... 
    // For every item in the list 
    for(String value: list) { 
     // print the value 
     System.out.println(value); 
    } 

什麼是「for-each」循環? http://download.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

還記得你可以使用索引隨機訪問ArrayList中的值。

ArrayList<String> list = new ArrayList<String>(); 
list.add("0"); 
list.add("1"); 

int index = 1; 
list.get(index); // You get the value 1 
0
//If just print out 
ArrayList<String[]> list = new ArrayList<String[]>(); 
... 
for(String[] item : list) { 
    //Use Arrays.toString 
    System.out.println(Arrays.toString(item)); 
} 
1
ArrayList<String[]> list = new ArrayList<String[]>(); 

for(int i=0; i<list.size(); i++){ 
    String[] stringArray = list.get(i); 

    for(String s : stringArray) { 
     System.out.println(s); 
    } 

    or 

    for(int j=0; j<stringArray.length; j++) { 
     System.out.println(stringArray[j]); 
    } 

} 
0

每個列表條目是字符串或null的陣列。

如果你有興趣在String[]對象,那麼我建議使用增強的for循環:

ArrayList<String[]> result = myMethodProvidingTheList(); 
for(String[] strings : result) { 
    if (strings != null { 
    doSomethingWith(strings); 
    } 
} 

如果您現在需要從陣列中的值,使用增強的for循環數組一樣的:

private void doSomethingWith(String[] strings) { 
    for (String string : strings) { 
    if (string != null) { 
     doSomethingWith(string); 
    } 
    } 
} 
相關問題