Java Modcount (ArrayList)
2022-09-01 03:47:14
在Eclipse中,我看到对象有一个字段。它的目的是什么?(修改次数?ArrayList
modCount
在Eclipse中,我看到对象有一个字段。它的目的是什么?(修改次数?ArrayList
modCount
它允许列表的内部人员知道是否进行了可能导致当前操作给出不正确结果的结构修改。
如果你在迭代列表时修改了一个列表(比如,删除一个项目),那么它的内部就是迭代器的提示。ConcurrentModificationException
modCount
AbstractList文档给出了一个很好的详细描述。
是的。如果你打算扩展 AbstractList
,你必须编写你的代码,以便它遵循 modCount 的 javadoc,如下所示:
/**
* The number of times this list has been <i>structurally modified</i>.
* 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.
*
* <p>This field is used by the iterator and list iterator implementation
* returned by the {@code iterator} and {@code listIterator} methods.
* If the value of this field changes unexpectedly, the iterator (or list
* iterator) will throw a {@code ConcurrentModificationException} in
* response to the {@code next}, {@code remove}, {@code previous},
* {@code set} or {@code add} operations. This provides
* <i>fail-fast</i> behavior, rather than non-deterministic behavior in
* the face of concurrent modification during iteration.
*
* <p><b>Use of this field by subclasses is optional.</b> If a subclass
* wishes to provide fail-fast iterators (and list iterators), then it
* merely has to increment this field in its {@code add(int, E)} and
* {@code remove(int)} methods (and any other methods that it overrides
* that result in structural modifications to the list). A single call to
* {@code add(int, E)} or {@code remove(int)} must add no more than
* one to this field, or the iterators (and list iterators) will throw
* bogus {@code ConcurrentModificationExceptions}. If an implementation
* does not wish to provide fail-fast iterators, this field may be
* ignored.
*/
查看实际的JDK源代码并阅读javadocs(在线或代码)有助于理解正在发生的事情。祝你好运。
我想补充一点,你可以将JDK源代码添加到Eclipse,以便每个F3或CTRL+单击任何Java SE类/方法都指向实际的源代码。如果下载 JDK,则应在 JDK 安装文件夹中有 src.zip。现在,在Eclipse的顶部菜单中,转到窗口»首选项»Java»已安装的JRE。选择当前 JRE 并单击“编辑”。选择 rt.jar 文件,单击“源附件”,单击“外部文件”,导航到 JDK 文件夹,选择 src.zip文件并添加。现在,Java SE API 的源代码在 Eclipse 中可用。JDK源代码提供了很多见解。快乐编码:)