public class IterableClass implements Iterable<String> {
protected String[] words = ("And that is how "+ "we know the Earth to be banana-shaped.").split(" ");
public Iterator<String> iterator(){ return new Iterator<String>(){ private int index=0; public boolean hasNext(){ System.out.println("a"); return index<words.length; } public String next(){ System.out.println("a"); return words[index++];
} public void remove(){ throw new UnsupportedOperationException(); } }; }
public static void main(String[] args) { // TODO Auto-generated method stub
for(String s : new IterableClass()){ System.out.println(s); } }
return new Iterator<String>(){
private int index=0;
public boolean hasNext(){
System.out.println("a");
return index<words.length;
}
public String next(){
System.out.println("a");
return words[index++];//最终就是从这里获取到words的
}
public void remove(){
throw new UnsupportedOperationException();
}
};
------解决方案--------------------
------解决方案-------------------- iterator迭代器~~~
------解决方案-------------------- iterator迭代器,其实跟for是一样的
------解决方案-------------------- 可能你是没有看明白增强型FOR吧 new IterableClass() 这个已经实现了Iterable 接口了,也就是拥有了这里面的遍历方法了。而且这种写法还是蛮值得推荐的!