`
pumbaa.he
  • 浏览: 71299 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

有关List和ConcurrentHashMap遍历时修改的问题

    博客分类:
  • java
 
阅读更多

List在迭代器遍历的时候,不能直接对List进行添加和删除,否则会报异常(删除可以用迭代器删除),所以这时候如果想对List进行操作的话,最好是把数据放到一个新的List里面,然后对新的List进行操作

 

List可以用for (int i = 0;i<list.size();i++)这种方式来遍历,这种遍历方式内部不锁定(遍历时添加删除不会报异常),效率最高,但是当写多线程时要考虑并发操作的问题

 

ConcurrentHashMap在迭代器遍历的时候,可以进行增删改的操作,如果增删改的操作在遍历的对象之前,那么就会在本次遍历的时候体现出来。

分享到:
评论
2 楼 世界杯2009 2018-03-30  
世界杯2009 写道
结论错的。反例在此
  @Test
    public void test() {
        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<String, String>();
        map.put("A", "A");
        map.put("B", "B");
        map.put("C", "C");
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            map.put("D", "D");
            map.remove("B", "B");
            map.put("C", "A");
            map.remove("C", "A");
            Map.Entry<String, String> next = iterator.next();
            System.out.printf("key:%s, value:%s\n", next.getKey(), next.getValue());
        }
    }


更正反例
@org.junit.Test
    public void test33() {
        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<String, String>();
        map.put("A", "A");
        map.put("B", "B");
        map.put("C", "C");
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            map.put("D", "D");
            map.remove("B", "B");
            map.put("C", "A");
            map.remove("A","A");
            Map.Entry<String, String> next = iterator.next();
            System.out.printf("key:%s, value:%s\n", next.getKey(), next.getValue());
        }
    }
输出,A没有移除掉
key:A, value:A
key:C, value:A
key:D, value:D
1 楼 世界杯2009 2018-03-30  
结论错的。反例在此
  @Test
    public void test() {
        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<String, String>();
        map.put("A", "A");
        map.put("B", "B");
        map.put("C", "C");
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            map.put("D", "D");
            map.remove("B", "B");
            map.put("C", "A");
            map.remove("C", "A");
            Map.Entry<String, String> next = iterator.next();
            System.out.printf("key:%s, value:%s\n", next.getKey(), next.getValue());
        }
    }

相关推荐

Global site tag (gtag.js) - Google Analytics