when modCount is initialized in java.util.ArrayList?

Viewed 350

I want to know when the field modCount of java.util.ArrayList is initialized.From the source code of java.util.ArrayList,we know the field modCount is inherited from java.util.AbstractList. And in the private inner class of java.util.ArrayList named Itr,its field expectedModCount is assigned from modCout,as shown below

enter image description here

In a demo,I debugged and found that itr.expectedModCount has been initialized.Because the value of expectedModCount is from modCount.So I looked up the source code to find when modCount is initialized,but failed.

enter image description here

2 Answers

It is initialized to 0 (note that it's an instance variable of the AbstractList super-class):

protected transient int modCount = 0;

and incremented in several places in which the List is structurally modified (i.e. elements are added or removed).

For example:

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

    modCount++;
    ....
}

Note that the Itr class is an inner class of ArrayList, and therefore it has access to the members of the enclosing ArrayList instance (which includes the modCount instance variable of the AbstractList super-class).

When I lookup where modCount is located I can find it, it's located inside java.util.AbstractList and is declared as:

protected transient int modCount = 0;

This means that it's initialized when it's declared.

Related