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 }

 

转载于:https://www.cnblogs.com/hebao0514/p/4851544.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值