選代器:是遍歷集合的一種方式。迭代器是依賴於集合而存在的。
我有一個集合: Collection c = new ArrayList();
咱們給集合中添加元素: c. add("hello' );c. add( "world」);c. add("java");java
集合的使用步驟:
A:建立集合對象B:建立元素對象
C:把元素添加到集合D:遍歷集合
a:經過集合對象獲取迭代器對象
b:經過迭代器對象的hasNext (方法判斷是否有元素
c:經過迭代器對象的next ()方法獲取元素並移動到下一個位置spa
例子:code
1 package com.wyh.Iterator; 2 3 import java.util.ArrayList; 4 import java.util.Collection; 5 import java.util.Iterator; 6 7 8 9 public class IteratorTest2 { 10 public static void main(String[] args) { 11 //建立集合容器 12 Collection c = new ArrayList(); 13 14 //實例化5個對象 15 Student s1 = new Student("王友虎",22); 16 Student s2 = new Student("李宏燦",21); 17 Student s3 = new Student("趙以浩",23); 18 Student s4 = new Student("李先鋒",24); 19 Student s5 = new Student("齊博源",25); 20 21 //將對象放進結合中 22 c.add(s1); 23 c.add(s2); 24 c.add(s3); 25 c.add(s4); 26 c.add(s5); 27 28 29 //將集合轉換成一個迭代器 30 Iterator it = c.iterator(); 31 32 33 //while循環輸出 34 //hasNext(),判斷迭代器裏是否有值,有返回true,無返回false 35 while(it.hasNext()) { 36 //System.out.println(it.next()); 37 //向下轉型 38 Student st = (Student)it.next(); 39 System.out.println("姓名"+st.getName()+" 年齡:"+st.getAge()); 40 41 } 42 43 44 45 46 } 47 48 }