简体   繁体   English

为什么不在LinkedList中定义ListIterator的静态类?

[英]Why not static class for the ListIterator defined in LinkedList?

I am reading the Java Doc for LinkedList's ListIterator, which is defined as a non-static inner class. 我正在为LinkedList的ListIterator读取Java Doc,它被定义为非静态内部类。 Why isn't it a static class? 为什么不是静态类? Shouldn't this data structure be shared among all instances of LinkedList? 不应该在LinkedList的所有实例之间共享此数据结构吗? I am confused. 我很困惑。 Thanks. 谢谢。

private class ListItr implements ListIterator<E>{

}

I think you have a slight misunderstanding of the difference between static and non-static classes vs. static and non-static members in Java: the difference between a static and non-static classes is that non-static classes have an implicit member holding a reference to the outer class, while a static class has no such implicit reference. 我认为你对静态类和非静态类与Java中的静态和非静态成员之间的区别有一点误解:静态类和非静态类之间的区别在于非静态类有一个隐式成员持有一个引用外部类,而静态类没有这样的隐式引用。 Both kinds of inner classes are shared among all instances; 两种内部类都在所有实例之间共享; it's instances of inner classes that are tied to instances of their outer classes. 它是被绑定到其外部类的实例内部类的实例

This is precisely what you want for iterators: each iterator is connected to the instance of the collection that it iterates, so it makes perfect sense to hold this reference implicitly by making the inner class non-static. 这正是迭代器所需要的:每个迭代器都连接到它迭代的集合的实例,因此通过使内部类非静态来隐式地保持这个引用是完全合理的。

First of all, ListItr is not a data structure, its an inner class. 首先, ListItr 不是数据结构,它是一个内部类。 ListIterator instances do not automatically share an instance of this class, and they should not! ListIterator实例不会自动共享此类的实例,它们不应该! As an inner class ListItr has access to its enclosing classes data, which is great for implementing an iterator over a collection of data. 作为内部类, ListItr可以访问其封闭类数据,这对于在数据集合上实现迭代器非常ListItr A static class would not have this level of access and as such would make a much poorer choice as the implementation of an iterator. 静态类具有此级别的访问权限,因此将作为迭代器的实现做出更差的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM