Java – fail fast iterator implementation

There are similar questions, but not exactly what I want to ask

This link says that its implementation exists in the abstractlist class, which defines an int variable modcount, which provides the number of times the list size has been changed This value is used in each next () call to check for any changes in the function checkforconfirmation()

But I really don't understand If the value is checked only after each next call, then if I perform a delete and then add the same call, the size will not change and modcount should not change But deleting and adding the same loop iteration will also throw an exception

Solution

If you look at the code of the collection implementation, let's choose ArrayList; We declare a modcount variable in abstractlist:

protected transient int modCount = 0;

Then in each modification method (such as remove) of the ArrayList we have

public E remove(int index) {
    rangeCheck(index);

    modCount++;
    //....

Therefore, modcount will only be incremented; It will never decrease

In iterator, we have:

final void checkForComodification() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

Where expectedmodcount is a snapshot of the modcount used when creating the iterator

Therefore, if you make any changes to the underlying list when using the same instance of iterator, you will throw a concurrentmodificationexception

I think there is a corner situation. If you make enough modifications, int will overflow and return its original value again - it will be a considerable number or modification, but; 232, to be exact

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>