首页 > 代码库 > foreach循环详解

foreach循环详解

在Java1.5+中,foreach循环非常实用.

 

技术分享
 1 public class Demo <T> implements Iterable<T>, Iterator<T> {
 2     T[] array;
 3     int length;
 4     int index;
 5 
 6     Demo(T[] param){
 7         array = param;
 8         length = array.length;
 9     }
10 
11     public static void main(String[] args) {
12         Demo<String> demo = new Demo<String>(new String[]{"aaa","bbb"});
13         for(String str : demo){
14             System.out.println(str);
15         }
16     }
17 
18     public Iterator<T> iterator(){
19         return this;
20     }
21 
22     public void remove(){
23     }
24 
25     public boolean hasNext(){
26         index = (index+1)%(length+1);
27         if(index==0)return false;
28         return true;
29     }
30 
31     public T next(){
32         return array[index-1];
33     }
34 }
35 
36 /*output:
37 aaa
38 bbb
39 */
点击+打开代码

 

上述代码等价于以下形式

1     public static void main() {
2         Demo<String> demo = new Demo<String>(new String[]{"aaa","bbb"});
3         Iterator<String> iterator = demo.iterator();
4         whlie(iterator.hasNext()){
5             String tmp = iterator.next();
6             System.out.println(tmp);
7         }
8     }

 

 

foreach循环详解