最近开发项目,频繁用到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()方法。
解决方案: