2

I'm reviewing linked lists in Java, learned them in C, and I noticed that I can use an iterator class to go through the linked list. But what I found strange is that they used a ListIterator to iterate forwards on the list (it can also be used to iterate backwards depending on where the pointer is), and Iterator to iterate backwards on the list. My question is, why can't we just use Iterator to iterate both forwards and backwards? What is the difference between the two?

Yitzak Hernandez
  • 355
  • 4
  • 23
  • 1
    `listIterator` adds multiple methods to move around the datastructure you're iterating – Lino Nov 13 '17 at 16:37
  • I can't tell where you are looking, but `DescendingIterator` actually implements `Iterator` and uses `ListItr` internally which in turn is used when iterating forward. Or did I miss your question here? – Eugene Nov 13 '17 at 16:46
  • @RiGid If an user answered your question please also accept his answer ([Accepting Answers: How does it work?](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)). If not then please specify what remains unanswered, this is a crucial part of StackOverflow, thank you very much. – Zabuzard Nov 14 '17 at 10:37

2 Answers2

2

Iterator

Iterator is a very general solution which should fit all data-structures, in fact you can iterate every class in Collection (documentation). But not every class there can ensure backwards-iterating simply due to their internal data-structure. For example a TreeSet which only knows its root element:

TreeSet structure

So Iterator tries to fit the common ability of all data structures to be at least iterable in one direction (documentation)


ListIterator

ListIterator is a special, not general, solution only useable for special List since they can, due to their internal structure, be iterated in both directions (and also allow adding and removing elements in between). This is not possible with other structures like TreeSet, so Collection doesn't offer ListIterator for all Collections, just List has it. From its documentation:

An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list.


To wrap it up, if Collection would offer a special Iterator like ListIterator then all implementing classes, also TreeSet and co. would need to implement this method. However those classes may not be able to meet that requirement (without heavy extra overhead).

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
1

From the API:

An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list.

Conversely, an Iterator can only iterate forwards.

jsheeran
  • 2,912
  • 2
  • 17
  • 32