2012-08-31 38 views
0

這裏是我的Java代碼:迭代器不能再重複

public static void main(String[] args) { 
    Map<String, String> map = new HashMap<String, String>(); 
    map.put("_name", "name"); 
    map.put("_age", "age"); 
    Set<String> set = map.keySet(); 
    Iterator iterator = set.iterator(); 
    // the first iteration 
    StringBuffer str1 = new StringBuffer(); 
    while (iterator.hasNext()) { 
     str1.append(iterator.next() + ","); 
    } 
    String str1To = str1.substring(0, str1.lastIndexOf(",")).toString(); 
    System.out.println(str1To); 
    // the second iteration 
    StringBuffer str2 = new StringBuffer(); 
    while (iterator.hasNext()) { 
     str2.append(iterator.next() + ","); 
    } 
    String str2To = str2.substring(0, str2.lastIndexOf(",")).toString();// ????? 
    System.out.println(str2To); 
} 

我的問題是,爲什麼沒有第二個循環迭代?第一次迭代是否已經完成iterator?這是什麼影響第二次迭代?

我該如何解決?

回答

3

您的第一個while循環會移動迭代,直至iterator到達列表的末尾。在那一刻,iterator本身就指向list的末尾,在你的情況下是map.keySet()。這就是爲什麼你的下一個while循環失敗,因爲iterator.hasNext()的調用返回false

一個更好的辦法是改用您while循環的Enhanced For Loop,像這樣:

for(String key: map.keySet()){ 
    //your logic 
} 
0

迭代器僅供一次性使用。所以再次請求迭代器。

0

每次你想迭代一個集合時,你需要調用set.iterator()。我建議你爲每次迭代使用一個不同的變量。