LinkedHashMap遍历的注意事项

LinkedHashMap的两种遍历方式

1. iterator

 LinkedHashMap<Integer,Integer>map=new LinkedHashMap<Integer,Integer>();
 //添加数据省略
 Iterator it=map.entrySet().iterator();
 while(it.hasNext()){
 	//it.next()返回object类型,需要强转
 	Map.Entry en=(Map.Entry)it.next();
 	System.out.println(en.getValue());
 }

2. foreach

LinkedHashMap<Integer,Integer>map=new LinkedHashMap<Integer,Integer>();
//添加数据省略
for(Map.Entry<Integer,Integer> en:map){
	System.out.println(en.getValue());
}

区别

对于第一种方式,有诸多需要注意的地方,如it.next()类型为object,同时还必须认识到,对于使用(Map.Entry)强转过来的en来说,它的getValue()返回的同样是object类型的;
对于第二种方法则不需要考虑这个问题,在这里getValue()将返回int类型

发布了11 篇原创文章 · 获赞 8 · 访问量 1452

猜你喜欢

转载自blog.csdn.net/qq_40783693/article/details/105632368
今日推荐