简体   繁体   English

在Java中增强了for循环和迭代器

[英]Enhanced for loop and iterator in Java

I have a class MyList that implements Iterable interface. 我有一个实现了Iterable接口的MyList类。 And here is a toString() method from one of my classes: 这是我的一个类中的toString()方法:

public String toString() {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 4; i++) {
        // First example using iterator
        for (Iterator<Integer> itr = array[i].iterator(); itr.hasNext();) {
            sb.append(itr.next() + " ");
        }
        // And the same result using enhanced for loop
        for (int val : array[i]) {
            sb.append(val + " ");
        }
    }
    return sb.toString();
}

This loop iterates over the nodes in my list: 这个循环遍历列表中的节点:

for (int val : array[i]) {
    sb.append(val + " ");
}

How does this for loop uses the iterator? 此for循环如何使用迭代器?

The enhanced for loop works for any class that implements Iterable . 增强的for循环可用于实现Iterable任何类。 It internally calls the iterator() method implemented by that class to obtain an Iterator , and uses hasNext() and next() methods of the Iterator to iterate over the elements of the Iterator . 它在内部调用由该类实现的iterator()方法以获得Iterator ,并使用Iterator hasNext()next()方法对Iterator的元素进行Iterator

Because your class ( MyList ) implements Iterable . 因为您的类( MyList )实现了Iterable So internally it will call your iterator() method and then with the use of hasNext() and next() methods of ListIterator it will iterate in for loop. 因此,在内部它将调用您的iterator()方法,然后使用hasNext()next()方法,将在for循环中进行迭代。

Refer : Using Enhanced For-Loops with Your Classes 请参阅:在类中使用增强型循环

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

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