集合遍历(迭代器遍历-
erator iterator():迭代器,集合的专用遍历方式 9 * Object next():获取元素,并移动到下一个位置。 10 * NoSuchElementException:没有这样的元素,因为你已经找到最后了。 11 * boolean hasNext():如果仍有元素可以迭代,则返回 true。---进行判断的语句
整体演示代码
注意:如果接受的对象是一个接口---则实际返回的肯定是子类的对象---多态--代码26行
1 package cn.itcast_03; 2 3 import java.util.ArrayList; 4 import java.util.Collection; 5 import java.util.Iterator; 6 7 /* 8 * Iterator iterator():迭代器,集合的专用遍历方式 9 * Object next():获取元素,并移动到下一个位置。 10 * NoSuchElementException:没有这样的元素,因为你已经找到最后了。 11 * boolean hasNext():如果仍有元素可以迭代,则返回 true。( 12 */ 13 public class IteratorDemo { 14 public static void main(String[] args) { 15 // 创建集合对象 16 Collection c = new ArrayList(); 17 18 // 创建并添加元素 19 // String s = "hello"; 20 // c.add(s); 21 c.add("hello"); 22 c.add("world"); 23 c.add("java"); 24 25 // Iterator iterator():迭代器,集合的专用遍历方式 26 Iterator it = c.iterator(); // 实际返回的肯定是子类对象,这里是多态 27 28 // Object obj = it.next(); 29 // System.out.println(obj); 30 // System.out.println(it.next()); 31 // System.out.println(it.next()); 32 // System.out.println(it.next()); 33 // System.out.println(it.next()); 34 // 最后一个不应该写,所以,我们应该在每次获取前,如果有一个判断就好了 35 // 判断是否有下一个元素,有就获取,没有就不搭理它 36 37 // if (it.hasNext()) { 38 // System.out.println(it.next()); 39 // } 40 // if (it.hasNext()) { 41 // System.out.println(it.next()); 42 // } 43 // if (it.hasNext()) { 44 // System.out.println(it.next()); 45 // } 46 // if (it.hasNext()) { 47 // System.out.println(it.next()); 48 // } 49 // if (it.hasNext()) { 50 // System.out.println(it.next()); 51 // } 52 53 // 最终版代码 54 while (it.hasNext()) { 55 // System.out.println(it.next()); 56 String s = (String) it.next(); 57 System.out.println(s); 58 } 59 } 60 }