1 package test_18_1; 2 3 import java.util.ArrayList; 4 import java.util.Collection; 5 import java.util.HashSet; 6 import java.util.Iterator; 7 import java.util.LinkedList; 8 import java.util.TreeSet; 9 10 public class IteratorTest { 11 12 static Collection fill(Collection<String> collection) { 13 14 for (int i = 0; i < 10; i++) { 15 collection.add("" + i); 16 } 17 18 return collection; 19 } 20 21 static void iterator(Iterator<String> it) { 22 while (it.hasNext()) { 23 String str = it.next(); 24 System.out.print(str.toString() + " "); 25 } 26 System.out.println(); 27 } 28 29 public static void main(String[] args) { 30 ArrayList<String> strAL = new ArrayList<String>(); 31 fill(strAL); 32 iterator(strAL.iterator()); 33 34 LinkedList<String> strLL = new LinkedList<String>(); 35 fill(strLL); 36 iterator(strLL.iterator()); 37 38 HashSet<String> strHS = new HashSet<String>(); 39 fill(strHS); 40 iterator(strHS.iterator()); 41 42 TreeSet<String> strTS = new TreeSet<String>(); 43 fill(strTS); 44 iterator(strTS.iterator()); 45 46 } 47 }
结果如下:
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9