下面是我的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带到了最后?这就是影响第二次迭代的因素吗?
我该如何修复它?
发布于 2012-08-31 11:11:29
您的第一个while循环将进行迭代,直到iterator到达列表的末尾。此时,iterator本身正指向list的末尾,在您的例子中是map.keySet()。这就是下一个while循环失败的原因,因为对iterator.hasNext()的调用返回false。
一种更好的方法是使用Enhanced For Loop,而不是while循环:
for(String key: map.keySet()){
//your logic
}发布于 2012-08-31 11:11:39
迭代器只能使用一次。因此,再次请求迭代器。
发布于 2012-08-31 11:11:51
每次要遍历集合时都需要调用set.iterator()。我建议您在每次迭代中也使用不同的变量。
https://stackoverflow.com/questions/12208365
复制相似问题