HashMap的迭代器问题,小郁闷
import java.util.*;import java.util.Map.Entry;//为何这里已经导入util.*了,还必须导入util.Map.Entry?public class T6 { public static void main(String[] args) { HashMap<String, String> hm = new HashMap<String, String>(); String email = "lily@sohu.com,tom@163.com,rock@sina.com"; String[] ss = email.split(","); for (String str : ss) { String name = str.substring(0, str.indexOf("@")); String url = str.substring(str.indexOf("@") + 1); hm.put(name, url); } //上边这一部分可以不看,关键是下边的迭代器部分,为何写成上边这种情况,运行时会输出第一个结果lily 163.com// 然后抛出如下异常 Exception in thread "main" java.util.NoSuchElementException// at java.util.HashMap$HashIterator.nextEntry(HashMap.java:796)// at java.util.HashMap$EntryIterator.next(HashMap.java:834)// at java.util.HashMap$EntryIterator.next(HashMap.java:832)// at t6.T6.main(T6.java:20)// Iterator<Entry<String, String>> it = hm.entrySet().iterator();// while (it.hasNext()) {//// System.out.println(it.next().getKey() + " " + it.next().getValue());// }//但是写成下面的却没有问题 Iterator<Entry<String, String>> it = hm.entrySet().iterator(); while (it.hasNext()) { Entry<String, String> entry = it.next(); System.out.println(entry.getKey() + " " + entry.getValue()); } }}