Foreach与迭代器

foreach语法主要用于数组,但也可以用于所有的Collection对象。

之所以能够工作是因为java se5引入了新的被称为Iterable的接口,该接口包含一个能够产生Iterator的iterator()方法,并且Iterable接口被foreach用来

在序列中移动。因此如果你创建了可以实现Iterable的类,都可以将他用于foreach语句中。

package example;

import java.util.Iterator;



public class Test implements Iterable<String> {
    protected String[] words=("And that is how"+"we know the earth to be banana-shaped").split(" ");
    public static void main(String[] args) {
        for(String s:new Test())
            System.out.print(s+" ");
    }

    public Iterator<String> iterator() {
        return new Iterator<String>() {    //匿名内部类
            private int index=0;

            public boolean hasNext() {
                
                return index<words.length;
            }

            public String next() {
                
                return words[index++];
            }

            public void remove() {
                throw new UnsupportedOperationException();
            }

            
        };
    }


}

output:And that is howwe know the earth to be banana-shaped

原文地址:https://www.cnblogs.com/xurui1995/p/5276562.html