问题
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