1 package test_20_3; 2 3 import java.util.Iterator; 4 5 class ArrayListTest { 6 7 protected String[] strArr = {"1", "2", "3", "4", "5", "6"}; 8 9 } 10 11 public class CollectionAndIteratorTest extends ArrayListTest { 12 13 // 生成Iterator是将队列与消费队列的方法连接在一起耦合度最小的方式 14 // 并且与实现Collection相比,它在序列类上所施加的约束也少得多 15 public Iterator<String> iterator(){ 16 17 return new Iterator<String>() { 18 19 private int index = 0; 20 21 @Override 22 public boolean hasNext() { 23 return index < strArr.length; 24 } 25 26 @Override 27 public String next() { 28 return strArr[index++]; 29 } 30 31 @Override 32 public void remove() { 33 throw new UnsupportedOperationException(); 34 } 35 36 }; 37 } 38 39 public static void display(Iterator<String> it) { 40 while (it.hasNext()) { 41 System.out.println(it.next()); 42 } 43 } 44 45 public static void main(String[] args) { 46 47 CollectionAndIteratorTest cai = new CollectionAndIteratorTest(); 48 display(cai.iterator()); 49 } 50 }
结果如下:
1
2
3
4
5
6