Exception in thread "main" java.util.ConcurrentModificationException at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013) at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967) at CollectionDelete.main(CollectionDelete.java:14)
privateclassItrimplementsIterator<E> { int cursor; // index of next element to return intlastRet= -1; // index of last element returned; -1 if no such intexpectedModCount= modCount;
// prevent creating a synthetic constructor Itr() {}
publicbooleanhasNext() { return cursor != size; }
@SuppressWarnings("unchecked") public E next() { checkForComodification(); inti= cursor; if (i >= size) thrownewNoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) thrownewConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; }
/** * Removes the first occurrence of the specified element from this list, * if it is present. If the list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * {@code i} such that * {@code Objects.equals(o, get(i))} * (if such an element exists). Returns {@code true} if this list * contained the specified element (or equivalently, if this list * changed as a result of the call). * * @param o element to be removed from this list, if present * @return {@code true} if this list contained the specified element */ publicbooleanremove(Object o) { final Object[] es = elementData; finalintsize=this.size; inti=0; found: { if (o == null) { for (; i < size; i++) if (es[i] == null) break found; } else { for (; i < size; i++) if (o.equals(es[i])) break found; } returnfalse; } fastRemove(es, i); returntrue; }
/** * Private remove method that skips bounds checking and does not * return the value removed. */ privatevoidfastRemove(Object[] es, int i) { modCount++; finalint newSize; if ((newSize = size - 1) > i) System.arraycopy(es, i + 1, es, i, newSize - i); es[size = newSize] = null; }
/** * Returns an iterator over the elements in this list in proper sequence. * * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>. * * @return an iterator over the elements in this list in proper sequence */ public Iterator<E> iterator() { returnnewItr(); }
abstractclassHashIterator { Node<K,V> next; // next entry to return Node<K,V> current; // current entry int expectedModCount; // for fast-fail int index; // current slot
HashIterator() { expectedModCount = modCount; Node<K,V>[] t = table; current = next = null; index = 0; if (t != null && size > 0) { // advance to first entry do {} while (index < t.length && (next = t[index++]) == null); } }
publicfinalbooleanhasNext() { return next != null; }
final Node<K,V> nextNode() { Node<K,V>[] t; Node<K,V> e = next; if (modCount != expectedModCount) thrownewConcurrentModificationException(); if (e == null) thrownewNoSuchElementException(); if ((next = (current = e).next) == null && (t = table) != null) { do {} while (index < t.length && (next = t[index++]) == null); } return e; }
publicfinalvoidremove() { Node<K,V> p = current; if (p == null) thrownewIllegalStateException(); if (modCount != expectedModCount) thrownewConcurrentModificationException(); current = null; removeNode(p.hash, p.key, null, false, false); expectedModCount = modCount; } }
/** * Removes from the underlying collection the last element returned * by this iterator (optional operation). This method can be called * only once per call to {@link #next}. * <p> * The behavior of an iterator is unspecified if the underlying collection * is modified while the iteration is in progress in any way other than by * calling this method, unless an overriding class has specified a * concurrent modification policy. * <p> * The behavior of an iterator is unspecified if this method is called * after a call to the {@link #forEachRemaining forEachRemaining} method. * * @implSpec * The default implementation throws an instance of * {@link UnsupportedOperationException} and performs no other action. * * @throws UnsupportedOperationException if the {@code remove} * operation is not supported by this iterator * * @throws IllegalStateException if the {@code next} method has not * yet been called, or the {@code remove} method has already * been called after the last call to the {@code next} * method */ defaultvoidremove() { thrownewUnsupportedOperationException("remove"); }
不能修改的原因
通过 Arrays.asList() 创建的 List 是一个固定大小的列表(fixed-size list),它不能直接进行结构性修改(如添加或删除元素)。这是因为 Arrays.asList() 返回的是一个由数组支持的 List 实现,而不是一个普通的 ArrayList。
ArrayList(E[] array) { a = Objects.requireNonNull(array); }
@Override publicintsize() { return a.length; }
@Override public Object[] toArray() { return Arrays.copyOf(a, a.length, Object[].class); }
@Override @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { intsize= size(); if (a.length < size) return Arrays.copyOf(this.a, size, (Class<? extendsT[]>) a.getClass()); System.arraycopy(this.a, 0, a, 0, size); if (a.length > size) a[size] = null; return a; }
@Override public E get(int index) { return a[index]; }
@Override public E set(int index, E element) { EoldValue= a[index]; a[index] = element; return oldValue; }
@Override publicintindexOf(Object o) { E[] a = this.a; if (o == null) { for (inti=0; i < a.length; i++) if (a[i] == null) return i; } else { for (inti=0; i < a.length; i++) if (o.equals(a[i])) return i; } return -1; }
publicabstractclassAbstractList<E> extendsAbstractCollection<E> implementsList<E> { /** * Sole constructor. (For invocation by subclass constructors, typically * implicit.) */ protectedAbstractList() { }
/** * Appends the specified element to the end of this list (optional * operation). * * <p>Lists that support this operation may place limitations on what * elements may be added to this list. In particular, some * lists will refuse to add null elements, and others will impose * restrictions on the type of elements that may be added. List * classes should clearly specify in their documentation any restrictions * on what elements may be added. * * @implSpec * This implementation calls {@code add(size(), e)}. * * <p>Note that this implementation throws an * {@code UnsupportedOperationException} unless * {@link #add(int, Object) add(int, E)} is overridden. * * @param e element to be appended to this list * @return {@code true} (as specified by {@link Collection#add}) * @throws UnsupportedOperationException if the {@code add} operation * is not supported by this list * @throws ClassCastException if the class of the specified element * prevents it from being added to this list * @throws NullPointerException if the specified element is null and this * list does not permit null elements * @throws IllegalArgumentException if some property of this element * prevents it from being added to this list */ publicbooleanadd(E e) { add(size(), e); returntrue; }