gkns
gkns

Reputation: 720

Why doesn't AbstractCollection implement iterator()?

From : Collections Framework

"the AbstractCollection class provides implementations for all the methods, except for the iterator() and size() methods, which are implemented in the appropriate subclass"

Could anyone make clear the reason why no default behavior for iterator() ? I could see why size () is not default from this question : Why does AbstractCollection not implement size()?

Upvotes: 1

Views: 483

Answers (3)

dMb
dMb

Reputation: 9367

Think of three different collections: a list based on an array, a linked list, and let's say sorted list based on a tree. An iterator for the array based collection would need to know who to access each element based on it's indexed location. An iterator for a linked list would need to know how to traverse the links between elements. And an iterator for a tree-based collection would need to know how to traverse a tree (for example breadth-first or depth-first). You can see that all these behaviors are very different and are implementation specific.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

The AbstractCollection does not know of how the data is stored, so there are two choices for the iterator() implementation:

  • Make it an abstract method, or
  • Throw UnsupportedOperationException the way it does for many other methods, such as add or remove.

Only the first solution makes sense: collections must allow at least reading, while writing may be optional.

Upvotes: 2

SLaks
SLaks

Reputation: 888203

What would it do?

The iterator() method is how the derived class actually provides the data.
All of the methods that AbstractCollection implements simply perform the appropriate logic using the data provided by the actual implementation in size() and iterator().

Upvotes: 6

Related Questions