无法从Map条目集中删除元素

时间:2014-04-19 06:05:51

标签: java map

这是我的程序

   public class MapTest{


   public static void main(String[] args) {
   Map<String, Integer> m = new LinkedHashMap<String, Integer>();
   m.put("John", 1);
   m.put("Mary", 2);
   m.put("Edward", 3);

   for (Map.Entry<String, Integer> e : m.entrySet())
   {

   e.remove();  //This line gives error.
   System.out.println(e.getKey() + ": " + e.getValue());
   }
   System.out.println("actual key "+m);

    }
    }

根据java docs Java Docs

  

Collection视图支持以多种形式删除元素 - remove,removeAll,retainAll和clear操作,以及Iterator.remove操作。 (再次,这假设支持Map支持元素删除。)

这里支持地图支持元素删除。那么为什么我无法删除该元素?

1 个答案:

答案 0 :(得分:0)

这不起作用,试试这个

    for (Iterator<Entry<String, Integer>> i = m.entrySet().iterator(); i.hasNext();) {
        Entry<String, Integer> e = i.next();
        i.remove();
        System.out.println(e.getKey() + ": " + e.getValue());
    }

没有args的Map.remove不存在,您可以尝试m.remove(e.getKey()),但随后您将获得ConcurrentModificationException。