1、必须继承AbstractCollection抽象类或其子类 并重写iterator方法(子类为重写iterator方法的)
2、循环是使用iterator方法返回的迭代器
3、迭代器实现iterator接口 并重写hasNext和next方法
AbstractList重写了iterator方法,故不用重写iterator。
AbstractSet:
/** * @author star * @since 6/27/2018 3:51 PM */ public class IteratorTest extends AbstractSet<String>{ private String [] strs={"1","2"}; @Override public Iterator<String> iterator() { return new MyIterator(); } @Override public int size() { return strs.length; } public class MyIterator implements Iterator<String> { int currentIndex=0; String next; @Override public boolean hasNext() { return currentIndex!=strs.length; } @Override public String next() { return strs[++currentIndex]; } } }
public static void main(String[] args) { IteratorTest iteratorTest=new IteratorTest(); for(String str:iteratorTest){ System.out.println(str); } }