What are the benefits of using an iterator in Java

后端 未结 6 1204
后悔当初
后悔当初 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条回答
  •  -上瘾入骨i
    2021-01-01 19:37

    Basically, foreach loop is a shortcut for the most common use of an iterator. This is, iterate through all elements. But there are some differences:

    • You can iterate through an array using foreach loop directly
    • You can remove objects using an iterator, but you can't do it with a foreach loop
    • Sometimes is useful to pass an iterator to a function (specially recursive ones)

提交回复
热议问题