Java基础知识强化之集合框架笔记09:Collection集合迭代器使用的问题探讨

1.Collection集合迭代器使用的问题探讨:

(1)问题1:能用while循环写这个程序,我能不能用for循环呢?  

                 可以使用for循环替代

(2)问题2:不要多次使用it.next()方法,因为每次使用都是访问一个对象

 1 package cn.itcast_03;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collection;
 5 import java.util.Iterator;
 6 
 7 /*
 8  * 问题1:能用while循环写这个程序,我能不能用for循环呢?  可以使用for循环替代
9 * 问题2:不要多次使用it.next()方法,因为每次使用都是访问一个对象。 10 */ 11 public class IteratorTest2 { 12 public static void main(String[] args) { 13 // 创建集合对象 14 Collection c = new ArrayList(); 15 16 // 创建学生对象 17 Student s1 = new Student("林青霞", 27); 18 Student s2 = new Student("风清扬", 30); 19 Student s3 = new Student("令狐冲", 33); 20 Student s4 = new Student("武鑫", 25); 21 Student s5 = new Student("刘晓曲", 22); 22 23 // 把学生添加到集合中 24 c.add(s1); 25 c.add(s2); 26 c.add(s3); 27 c.add(s4); 28 c.add(s5); 29 30 // 遍历 31 Iterator it = c.iterator(); 32 while (it.hasNext()) { 33 Student s = (Student) it.next(); 34 System.out.println(s.getName() + "---" + s.getAge()); 35 36 // NoSuchElementException 不要多次使用it.next()方法,这里会导致拿了第1个人名字 对应 第2个人的年龄;第3个人名字 对应 第4个人年龄…… 37 // System.out.println(((Student) it.next()).getName() + "---" 38 // + ((Student) it.next()).getAge()); 39 40 } 41 // System.out.println("----------------------------------"); 42 43 // for循环改写 44 // for(Iterator it = c.iterator();it.hasNext();){ 45 // Student s = (Student) it.next(); 46 // System.out.println(s.getName() + "---" + s.getAge()); 47 // } 48 } 49 }

 

posted on 2015-10-01 20:57  鸿钧老祖  阅读(153)  评论(0编辑  收藏  举报

导航