在Java1.5+中,foreach循环非常实用.
public class Demo <T> implements Iterable<T>, Iterator<T> {
T[] array;
int length;
int index; Demo(T[] param){
array = param;
length = array.length;
} public static void main(String[] args) {
Demo<String> demo = new Demo<String>(new String[]{"aaa","bbb"});
for(String str : demo){
System.out.println(str);
}
} public Iterator<T> iterator(){
return this;
} public void remove(){
} public boolean hasNext(){
index = (index+1)%(length+1);
if(index==0)return false;
return true;
} public T next(){
return array[index-1];
}
} /*output:
aaa
bbb
*/
点击+打开代码
上述代码等价于以下形式
public static void main() {
Demo<String> demo = new Demo<String>(new String[]{"aaa","bbb"});
Iterator<String> iterator = demo.iterator();
whlie(iterator.hasNext()){
String tmp = iterator.next();
System.out.println(tmp);
}
}