在做项目中用到List存储数据,在里面做数据操作时候用到了删除.结果抛出ConcurrentModificationException异常.在这里把问题总结一下. 原因: ArrayList进行foreach时所调用的迭代器(内部迭代器Itr) /** * An optimized version of AbstractList.Itr */ private class Itr implements Iterator<E> { int cursor; // index of next elem…
一.ConcurrentModificationException ArrayList源码看为什么出现异常: public class ArrayList<e> extends AbstractList<e> implements Cloneable, Serializable, RandomAccess { @Override public boolean remove(Object object) { Object[] a = array; int s = size; if (…
java中两种基本的集合结构ArrayList和LinkedList底层有两种不同的存储方式实现,ArrayList为数组实现,属于顺序存储,LinkedList为链表实现,属于链式存储,在对ArrayList做迭代删除时,会出现ConcurrentModificationException public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add(&…
//从一个ArrayList中删除重复元素 List<String> arrayList1 = new ArrayList<String>(); arrayList1.add("C"); arrayList1.add("A"); arrayList1.add("B"); arrayList1.add("A"); arrayList1.add("B"); arrayList1.add(…
最朴实的方法,使用下标的方式: ArrayList<String> al = new ArrayList<String>(); al.add("a"); al.add("b"); //al.add("b"); //al.add("c"); //al.add("d"); for (int i = 0; i < al.size(); i++) { if (al.get(i) ==…
一.背景 在以前的随笔中说道过ArrayList的foreach迭代删除的问题:ArrayList迭代过程删除问题 按照以前的说法,在ArrayList中通过foreach迭代删除会抛异常:java.util.ConcurrentModificationException 但是下面这段代码实际情况却没报异常,是什么情况? List<String> list = new ArrayList<String>(); list.add("1"); list.add(&q…
引言 前几天有个读者由于看了<ArrayList哪种遍历效率最好,你真的弄明白了吗?>问了个问题普通for循环ArrayList为什么不能删除连续重复的两个元素?其实这个描述是不正确的.正确的应该是普通for循环正序删除,不能删除连续的元素所以就产生了这个文章. ArrayList删除数据的方式 我们先看下ArrayList总共有几种删除元素的方法吧. package com.workit.demo.array; import java.util.ArrayList; import java.…
ArrayList关键属性分析 ArrayList采用Object数组来存储数据 /** * The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. 何问起 hovertree.com */ transient Object[] elementData; // non-priva…
List<E> subList(int fromIndex,int toIndex) 该方法返回原有集合从fromIndex 到 toIndex之间一部分数据,组成一个新的集合,这两个集合之间是有联系的. 1:你对原来的集合与返回的集合做非结构性的修改,都会影响到对方. 2:如果你对原来的集合进行结构性的修改,在使用返回的子List语义上将会是undefined, 使用的时候将会抛出        ConcurrentModificationException异常 List<String…
欢迎关注我的公众号"彤哥读源码",查看更多源码系列文章, 与彤哥一起畅游源码的海洋. 简介 ArrayList是一种以数组实现的List,与数组相比,它具有动态扩展的能力,因此也可称之为动态数组. 继承体系 ArrayList实现了List, RandomAccess, Cloneable, java.io.Serializable等接口. ArrayList实现了List,提供了基础的添加.删除.遍历等操作. ArrayList实现了RandomAccess,提供了随机访问的能力.…