List的2个错误用法

来源:互联网 发布:铁路造价软件培训 编辑:程序博客网 时间:2024/06/04 23:16

最近开发项目,频繁用到ArrayList,犯了两个错误

错误1:String[] testStrings = new String[]{"22","23","24"};

List<String> testtList = Arrays.asList(testStrings);

testtList.add("25");

testtList.remove("22");------报java.lang.UnsupportedOperationException错误

问题原因:Arrays.asList(testStrings)返回的类没有remove(oject)方法;

解决方案:声明为AarrayList类对象List<String> intList = new ArrayList<String>(Arrays.asList(testStrings));

错误2:遍历arrayList时,删除元素,报java.util.ConcurrentModificationException异常

        for(String aa : intList)
        {
            if(aa.contains("2"))
            {
                intList.remove(aa);
            }
        }

问题原因:(转载)执行remove(Object o)方法之后,modCount和expectedModCount不相等了。然后当代码执行到next()方法时,判断了checkForComodification(),发现两个数值不等,就抛出了该Exception。
要避免这个Exception,就应该使用remove()方法。

解决方案:

 

0 0
原创粉丝点击