简体   繁体   中英

What is the benefit of using Iterator instead of ListIterator for ArrayList?

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?

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.

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.

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

Now, if you implement some really List -based operation, you actually want to operate on List s 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 List s but on any data structure which implements Iterable , including all kinds of Collection s. This makes your code more generic and flexible to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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