ConcurrentModificationException
来源:互联网 发布:apache源码包下载地址 编辑:程序博客网 时间:2024/05/16 19:10
最近写代码竟然烦了一个很低级的错误,写出来供大家参考:
在涉及到map或者list删除的时候,我们经常写出如下错误代码:
结果编译器报错Exception in thread "main" java.util.ConcurrentModificationException
正确代码如下:
仅仅相差一个it.remove(str),你是不是也经常马虎呢?
其实,Iterator可以理解为一个索引,他依靠在其所要迭代的集合上,一旦使用lhm.remove,就会使原来的集合结构遭到破坏,此时原来的集合与iterator的索引结构不一致,自然iterator就会报错。而用iteraotr.remove(),iterator会自动的维护被迭代集合的索引一致性,因此能够正常运行。
在涉及到map或者list删除的时候,我们经常写出如下错误代码:
LinkedHashMap<String,String> lhm=new LinkedHashMap<String,String>();lhm.put("a","a");lhm.put("b","b");lhm.put("c","c");lhm.put("d","d");Iterator<String> it=lhm.keySet().iterator();while(it.hasNext()){ String str=it.next(); if("a".equals(str)) lhm.remove(str);}
结果编译器报错Exception in thread "main" java.util.ConcurrentModificationException
正确代码如下:
LinkedHashMap<String,String> lhm=new LinkedHashMap<String,String>();lhm.put("a","a");lhm.put("b","b");lhm.put("c","c");lhm.put("d","d");Iterator<String> it=lhm.keySet().iterator();while(it.hasNext()){ String str=it.next(); if("a".equals(str)) it.remove(str);}
仅仅相差一个it.remove(str),你是不是也经常马虎呢?
其实,Iterator可以理解为一个索引,他依靠在其所要迭代的集合上,一旦使用lhm.remove,就会使原来的集合结构遭到破坏,此时原来的集合与iterator的索引结构不一致,自然iterator就会报错。而用iteraotr.remove(),iterator会自动的维护被迭代集合的索引一致性,因此能够正常运行。
0 0
- ConcurrentModificationException
- ConcurrentModificationException
- ConcurrentModificationException
- ConcurrentModificationException
- ConcurrentModificationException
- ConcurrentModificationException
- ConcurrentModificationException
- ConcurrentModificationException
- ConcurrentModificationException
- ConcurrentModificationException
- ConcurrentModificationException
- ConcurrentModificationException
- ConcurrentModificationException
- ConcurrentModificationException
- ConcurrentModificationException
- ConcurrentModificationException
- ConcurrentModificationException
- ConcurrentModificationException 异常
- 一个自定义注释的例子
- 反射机制实现方法调用
- java实现简单AOP(二)
- ubuntu14.04设置静态IP
- TensorFlow 博文转载
- ConcurrentModificationException
- ubuntu删除特定用户的进程
- itext将html转pdf中文支持
- Ubuntu14.04安装jdk1.7.0_71
- 给定RGB值计算色谱上相应的坐标
- android资源的热更新(替换 AssetManager+LoadedApk中的资源路径)
- Java Web开发--------监听器
- ubuntu实现无密码登陆
- ubuntu14.04的hadoop环境搭建(全分布模式)