今天写代码出现错误:Exception in thread "main" java.util.NoSuchElementException
如下图:
package cn.itsast.day13集合.Map集合.demo01Map集合的概述和遍历;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/*
Map集合遍历的第二种方式:使用Entry对象遍历
Map集合中的方法:
Set<Map.Entry<K,V>> entrySet() 返回此映射中包含的映射关系的 Set 视图。
实现步骤:
1.使用Map集合中的方法entrySet(),把Map集合中多个Entry对象取出来,存储到一个Set集合中
2.遍历Set集合,获取每一个Entry对象
3.使用Entry对象中的方法getKey()和getValue()获取键与值
*/
public class Demo03EntrySet {
public static void main(String[] args) {
//创建map集合对象:键值对存储姓名和身高
Map<String,Integer> map = new HashMap<>();
map.put("姚明",220);
map.put("项羽",200);
map.put("武大郎",130);
//1.使用Map集合中的方法entrySet(),把Map集合中多个Entry对象取出来,存储到一个Set集合中
Set<Map.Entry<String, Integer>> set = map.entrySet();
//2,遍历Set集合,获取每一个Entry对象
//使用迭代器遍历Set集合
Iterator<Map.Entry<String ,Integer>> it = set.iterator();
while (it.hasNext()){
Map.Entry<String, Integer> entry = it.next();
it.next();
//使用Entry对象中的方法getKey(),getValue获取键值对
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key+"="+value);
}
}
}
解决方法:删掉while循环中的:it.next();