迭代器不能再次迭代

时间:2012-08-31 03:05:36

标签: java iterator

这是我的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 个答案:

答案 0 :(得分:3)

您的第一个while循环将迭代移动,直到iterator到达列表的末尾。在那一刻,iterator本身指向list的末尾,在您的情况下是map.keySet()。这就是为什么您的下一个while循环失败的原因,因为对iterator.hasNext()的调用会返回false

更好的方法是使用Enhanced For Loop,而不是while循环:

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

答案 1 :(得分:0)

Iterator仅供一次使用。所以再次要求迭代器。

答案 2 :(得分:0)

每次想要遍历集合时,都需要调用set.iterator()。我建议你为每次迭代使用不同的变量。