1

From what I understand, ListIterator provides much more functionality than Iterator for lists. If so, why use Iterator at all? Is there an optimization or performance factor to it as well?

skylight
  • 11
  • 2
  • 1
    You can refer : http://stackoverflow.com/a/17939167/3226981 – Suyash Feb 15 '16 at 10:12
  • 1
    Only lists have a ListIterator. Sets, and collections only have an iterator – Ferrybig Feb 15 '16 at 10:12
  • 1
    Possible duplicate of [Difference between Iterator and Listiterator?](http://stackoverflow.com/questions/10977992/difference-between-iterator-and-listiterator) – phoenix Feb 15 '16 at 11:33

3 Answers3

0

Generally the less your code knows about other parts of code and data structures the better. The reason is simple: this simplifies the modification.

Indeed, Collection is more powerful than Iterator, List is more powerful than Collection.

But Iterator can be obtained from a lot of data structures, so if you are using Iterator that you get from (for example) list you can than change your code and get iterator from (for example) database without changing code that works with iterator.

AlexR
  • 114,158
  • 16
  • 130
  • 208
  • "more powerful than Iterator" - Did you mean `Iterable`? – JimmyB Feb 15 '16 at 10:34
  • No, I mean `Collection`. Iterable is just an accessor to `Iterator` with additional compiler magic named `for(:)` – AlexR Feb 15 '16 at 12:21
  • `List` is a `Collection` is an `Iterable`, hence `List` "is more powerful than" `Collection` just as `Collection` "is more powerful than" `Iterable`... – JimmyB Feb 15 '16 at 14:00
0

Use the ListIterator to express the requirement to iterate in a specific order. Use the Iterator to express that order does not matter.

Generally I think that the use of iterators makes code difficult to read. I don't know your use case but in most cases it makes sense to use the enhanced for loop or a functional approach like Java 8 streams instead.

Frank Puffer
  • 8,135
  • 2
  • 20
  • 45
0

If you need functionality of ListIterator then you can use it. At the same time, you restrict yourself to operating on Lists at that specific place.

Now, if you implement some really List-based operation, you actually want to operate on Lists only, so maybe that's no restriction for you.

If, however, you don't really need the special funtionality of ListIterator but an Iterator is sufficient, then prefer using the plain Iterator; this enables you to operate not only on Lists but on any data structure which implements Iterable, including all kinds of Collections. This makes your code more generic and flexible to use.

JimmyB
  • 12,101
  • 2
  • 28
  • 44