日期:2014-05-20  浏览次数:20727 次

Thinking in java 这本书的一道问题

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);
}
}

}
为什么new IterableClass()直接写这个就可以遍历到words数组呢?
而且直接就进入匿名内部类的重写方法中,这是什么原理

------解决方案--------------------
Iterable<String>实现了这个接口之后就允许使用foreach遍历,泛型String就是每个元素类型
实现该接口的方法iterator(),在使用foreach遍历时就会通过iterator的返回值来遍历,也就是你的匿名内部类的实例
Java code
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();
}
};

------解决方案--------------------
探讨

Iterable<String>实现了这个接口之后就允许使用foreach遍历,泛型String就是每个元素类型
实现该接口的方法iterator(),在使用foreach遍历时就会通过iterator的返回值来遍历,也就是你的匿名内部类的实例
Java code
return new Iterator<String>(){
private int index=0;
public bool……

------解决方案--------------------
iterator迭代器~~~
------解决方案--------------------
iterator迭代器,其实跟for是一样的
------解决方案--------------------
可能你是没有看明白增强型FOR吧
new IterableClass() 这个已经实现了Iterable 接口了,也就是拥有了这里面的遍历方法了。而且这种写法还是蛮值得推荐的!

------解决方案--------------------
iterator迭代器,其实跟for是一样的
------解决方案--------------------
new了一个内部内,然后return了。