What are the benefits of using an iterator in Java

后端 未结 6 1335
后悔当初
后悔当初 2021-01-01 19:10

I was browsing over the following code example:

public class GenericTest {
  public static void main (String[] args) {
    ArrayList myList = ne         


        
6条回答
  •  梦谈多话
    2021-01-01 19:38

    An iterator is an abstraction over how a collection is implemented. It lets you go over the whole collection one item at a time, optionally removing items.

    The disadvantage of an Iterator is that it can be a lot slow if you DO know the underlying implementation. For example using an Iterator for an ArrayList is considerable slower than just calling ArrayList.get(i) for each element. Whether this matters much depends on what the code is doing.

提交回复
热议问题