Why ArrayList's non-static inner class SubList has a member variable “parent”?

折月煮酒 提交于 2021-01-27 07:20:50

问题


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?

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.


回答1:


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);
    }

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

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



来源:https://stackoverflow.com/questions/21923674/why-arraylists-non-static-inner-class-sublist-has-a-member-variable-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!