map的遍历方式和使用注意事项

map的遍历方式和使用注意事项 .
public class TestMap
{
   1.map遍历过程中不可以remove掉其中的元素,否则异常
   解决方案:遍历时将要删除的key添加到list里面
   之后再在list遍历删除map里的值
   2.在java bean中直接创建map,list,不用设setter,getter方法(用不到而且难以理解)
   3.注意map的便利方法(独特)
 public static void main(String[] args)
 {
  Map<String, Integer> randomMap = new HashMap<String, Integer>();
  randomMap.put("abc", 1000);
  randomMap.put("www", 2000);
  randomMap.put("dddd", 3000);
 

/**

 这个效率相对低点
m.keySet().iterator()
以后最好用下面这个
jmap.entrySet().iterator()

*/


                List<String> list = new ArrayList<String>();
//  Iterator iter = randomMap.keySet().iterator();
 
  while (iter.hasNext())   //map的便利方法(独特)
                {
   String key = iter.next().toString();
  
   int val = randomMap.get(key);
  
   if(val> 1000)
   {
    list.add(key);
   }
         }
 
  for (int i = 0; i < list.size(); i++)
  {
   //list存储的是key,应该为randomMap.remove(list.get(i)),而不           

            //是randomMap.remove(i)
                        randomMap.remove(list.get(i));
  }
 
 }

}

posted @ 2013-06-14 23:23  嗨,你的益达~~~  阅读(365)  评论(0编辑  收藏  举报