Why does an ArrayList non-static inner SubList class have a member variable of "parent"?

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

My jdk is the latest and I searched google to get the latest java.util.ArrayList source code. 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 on my computer.

+4
source share
1 answer

Your conclusion in the comments is correct. SubLista field is required parentbecause it is SubListused SubListas a parent in subcategories - the nested is ArrayListnot the parent. In particular, the source ArrayList.SubList.subList () :

    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 one SubList.

parent.

+3

Source: https://habr.com/ru/post/1528013/


All Articles