user697911
user697911

Reputation: 10531

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. Why isn't it a static class? Shouldn't this data structure be shared among all instances of LinkedList? I am confused. Thanks.

private class ListItr implements ListIterator<E>{

}

Upvotes: 0

Views: 446

Answers (2)

Perception
Perception

Reputation: 80603

First of all, ListItr is not a data structure, its an inner class. ListIterator instances do not automatically share an instance of this class, and they should not! As an inner class ListItr has access to its enclosing classes data, which is great for implementing an iterator over a collection of data. 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.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726649

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

Upvotes: 2

Related Questions