简体   繁体   English

对ArrayList使用Iterator而不是ListIterator有什么好处?

[英]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. 据我了解,ListIterator提供了比Iterator列表更多的功能。 If so, why use Iterator at all? 如果是这样,为什么还要使用Iterator? 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 . 实际上, CollectionIterator更强大, ListCollection更强大。

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. 但是Iterator可以从许多数据结构中获取,因此,如果您使用的是从(例如)列表中获取的Iterator,则可以更改代码并从(例如)数据库中获取迭代器,而无需更改与Iterator一起使用的代码。

Use the ListIterator to express the requirement to iterate in a specific order. 使用ListIterator表示以特定顺序进行迭代的要求。 Use the Iterator to express that order does not matter. 使用Iterator表示该顺序无关紧要。

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. 我不知道您的用例,但是在大多数情况下,使用增强的for循环或Java 8流之类的功能方法是有意义的。

If you need functionality of ListIterator then you can use it. 如果您需要ListIterator功能,则可以使用它。 At the same time, you restrict yourself to operating on List s at that specific place. 同时,您限制自己只能在该特定位置对List进行操作。

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. 现在,如果您实现了一些真正的基于List的操作,则实际上您只想List进行操作,因此这对您没有限制。

If, however, you don't really need the special funtionality of ListIterator but an Iterator is sufficient, then prefer using the plain Iterator ; 但是,如果你并不真正需要的特殊funtionality ListIterator而是一个Iterator就足够了,那么喜欢用普通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. 这使您不仅可以对List进行操作,而且还可以对实现Iterable任何数据结构进行操作,包括各种Collection This makes your code more generic and flexible to use. 这使您的代码更通用,使用更灵活。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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