package yzhou.iterator; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; public class Test01 { public static void main(String[] args) { List list = new ArrayList(); list.add("aaa"); list.add("bbb"); list.add("ccc"); //通过索引遍历List for(int i=0;i<list.size();i++) { System.out.println(list.get(i)); } //通过迭代器遍历List for(Iterator iter2 = list.iterator();iter2.hasNext();) { String str = (String) iter2.next(); System.out.println(str); iter2.remove(); } System.out.println(list.size()+"************************************"); Set set = new HashSet(); set.add("zhangsan1"); set.add("zhangsan2"); set.add("zhangsan3"); // Iterator iter = set.iterator(); // while(iter.hasNext()) // { // String str = (String)iter.next(); // System.out.println(str); // } for(Iterator iter = set.iterator();iter.hasNext();) { String str = (String)iter.next(); System.out.println(str); } } }
单独说下:
for(Iterator iter = set.iterator();iter.hasNext();) { String str = (String)iter.next(); System.out.println(str); }
这里是for 与 iterator 都用到了,
for的执行步骤:
先初始化值
判断
执行函数体
赋值++/--
判断
执行函数体
……