专业购物网站建设价格,铁岭建设银行网站,网站推广常用方法包括,个人网站建站源码今天在测试代码的时候出现一个异常ConcurrentModificationException#xff0c;该异常网上很多解决方案以及解释#xff0c;但我还是再记录一遍吧。代码抽象出来是这样的#xff1a;import java.util.ArrayList;import java.util.List;public class Test {public static voi…今天在测试代码的时候出现一个异常ConcurrentModificationException该异常网上很多解决方案以及解释但我还是再记录一遍吧。代码抽象出来是这样的import java.util.ArrayList;import java.util.List;public class Test {public static void main(String[] args) {List listnew ArrayList();list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);for (Integer i : list) {//这是迭代if(i3){list.remove(new Integer(i));//引起异常的操作}}}}该代码在运行期间就出现java.util.ConcurrentModificationException异常。这个循环其实是对list进行迭代。1.在迭代的时候怎么判断是否还有下一个(hasNext()方法怎么实现)public boolean hasNext() {return cursor ! size();}cursor:Index of element to be returned by subsequent call to nextsize():是该list的size所以只要两者不相等就认为还有元素。2.迭代的时候怎么取下一个(next()方法怎么实现)public E next() {checkForComodification();try {E next get(cursor);lastRet cursor;return next;} catch (IndexOutOfBoundsException e) {checkForComodification();throw new NoSuchElementException();}}final void checkForComodification() {if (modCount ! expectedModCount)throw new ConcurrentModificationException();}modelCount:The number of times this list has been structurally modified.Structural modifications are those that change the size of the list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.expectedModCount:期望的modelCount这2个变量是有迭代器自己来维护的。上面这段程序出现异常是因为我们使用Collection里面的remove方法进行删除ArrayList的remove方法实现public boolean remove(Object o) {if (o null) {for (int index 0; index size; index)if (elementData[index] null) {fastRemove(index);return true;}} else {for (int index 0; index size; index)if (o.equals(elementData[index])) {fastRemove(index);return true;}}return false;}private void fastRemove(int index) {modCount; //***int numMoved size - index - 1;if (numMoved 0)System.arraycopy(elementData, index1, elementData, index,numMoved);elementData[--size] null; // Let gc do its work}modCount1,导致modCount和expectedModCount不相等。3.解决方法就是用迭代器自己的remove方法public void remove() {if (lastRet -1)throw new IllegalStateException();checkForComodification();try {AbstractList.this.remove(lastRet); //将modCount1实现如下if (lastRet cursor)cursor--;lastRet -1;expectedModCount modCount; //维护} catch (IndexOutOfBoundsException e) {throw new ConcurrentModificationException();}}public E remove(int index) {RangeCheck(index);modCount; //***E oldValue (E) elementData[index];int numMoved size - index - 1;if (numMoved 0)System.arraycopy(elementData, index1, elementData, index,numMoved);elementData[--size] null; // Let gc do its workreturn oldValue;}