【发布时间】:2018-05-18 17:49:49
【问题描述】:
我正在阅读有关 ConcurrentModificationException 的信息。我为迭代器找到了这段代码。谁能解释导致这个异常的真正原因。我只想为下面写的逻辑提供一些理由。
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
【问题讨论】:
-
您有什么具体问题吗? “那里有一些我不理解的代码”不是问题,这是事实,因为任何人一生都可以理解更多的代码。至少乍一看,这段特定的代码看起来不错。
-
当然,代码看起来不错。但我无法理解这些行: Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException();
标签: java collections concurrency iterator concurrentmodification