本文介绍了为什么ArrayList的非静态内部类SubList具有成员变量"parent"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java.util.ArrayList.SubList是java.util.ArrayList的一个非静态内部类类,这意味着它持有对其封闭类的引用.我们可以使用ArrayList.this访问java.util.ArrayList的成员.但是java.util.ArrayList.SubList也有一个成员"parent",它也是对java.util.ArrayList.SubList的封闭类的引用.为什么需要父"成员变量,或者为什么不将java.util.ArrayList.SubList声明为静态内部类?

java.util.ArrayList.SubList is a non-static inner class class of java.util.ArrayList, which means that it holds an reference to its enclosing class. We can access the members of java.util.ArrayList by using ArrayList.this. But java.util.ArrayList.SubList also has a member "parent" which is also a reference to the enclosing class of java.util.ArrayList.SubList. Why the "parent" member variable is needed or why not declare java.util.ArrayList.SubList as a static inner class?

我的jdk是最新的,并且我已经在Google上搜索了java.util.ArrayList的最新源代码.我得到以下链接: http://www.docjar.com/html/api/java/util/ArrayList.java.html .页面上的代码与我的计算机上的代码相同.

My jdk is the latest, and I had searched google for the latest source code of java.util.ArrayList. I got the following link:http://www.docjar.com/html/api/java/util/ArrayList.java.html. The code on the page is the same as that on my computer.

推荐答案

您在注释中的结论是正确的. SubList 需要一个 parent 字段,因为 SubList 的子列表使用 SubList 作为父级-封闭在这种情况下, ArrayList 不是父级.特别是 ArrayList.SubList.subList()是:

Your conclusion in the comments is correct. SubList requires a parent field because sub-lists of a SubList use the SubList as the parent -- the enclosing ArrayList is not the parent in that case. In particular, the source for ArrayList.SubList.subList() is:

    public List<E> subList(int fromIndex, int toIndex) {
        subListRangeCheck(fromIndex, toIndex, size);
        return new SubList(this, offset, fromIndex, toIndex);
    }

请注意,此 this (一个 SubList )作为父参数传递给新的 SubList .

Note that this (a SubList) is passed as the parent parameter to the new SubList.

没有显式的 parent 字段,将无法跟踪.

There would be no way to track this without an explicit parent field.

这篇关于为什么ArrayList的非静态内部类SubList具有成员变量"parent"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-01 01:58