迭代器iterator不能再次迭代吗

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();
        // 第一次迭代
        StringBuffer str1 = new StringBuffer();
        while (iterator.hasNext()) {
            str1.append(iterator.next() + ",");
        }
        String str1To = str1.substring(0, str1.lastIndexOf(",")).toString();
        System.out.println(str1To);
        // 第二次迭代
        StringBuffer str2 = new StringBuffer();
        while (iterator.hasNext()) {
            // 断点调式好像不会进入到这里面来
            str2.append(iterator.next() + ",");
        }
        String str2To = str2.substring(0, str2.lastIndexOf(",")).toString();// 这一行报错
        System.out.println(str2To);
    }

 

代码如上,两次迭代为什么不行,难道是第一次迭代的时候已经迭代到最后了吗?这样会影响到第二次迭代?

第一次已经到尾部了,第二次迭代的那个循环就不去,所以str2里面没有内容, str2.substring(0, -1)报StringIndexOutOfBoundsException的异常。

如果你想重新迭代,重新获取一下iterator就可以了: itrator = str1.iterator(),这样就从头开始了。

第一次迭代已经到最后,所以迭代才会结束;如果需要再次使用,需要重新获取迭代器(set.iterator())。
看一段jdk中Interator.next()的实现源码,就会明白原理了。
AbstractList中的内部类Itr部分源码如下:
[code="java"]
private class Itr implements Iterator {

/**

  • Index of element to be returned by subsequent call to next. */
    int cursor = 0;

/**

  • Index of element returned by most recent call to next or
  • previous. Reset to -1 if this element is deleted by a call
  • to remove. */
    int lastRet = -1;

public boolean hasNext() {

return cursor != size();

}

public E next() {

checkForComodification();

try {

E next = get(cursor);

lastRet = cursor++;

return next;

} catch (IndexOutOfBoundsException e) {

checkForComodification();

throw new NoSuchElementException();

}

} [/code]

迭代一次迭代完毕。如果需要再次迭代。用iterator()这个方法。

迭代完了就不能迭代了,重新拿一个迭代器迭代,如果一直用一个 就不叫迭代器了