• 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 }
  • 相关阅读:
    Triangle
    Populating Next Right Pointers in Each Node II
    Populating Next Right Pointers in Each Node
    面试题之判断栈的入栈和出栈序列的合法性
    对称矩阵的压缩存储和输出
    栈的经典面试题之用两个栈实现一个队列
    C++的三大特性之一继承
    C++之类的析构函数
    malloc函数的底层实现你是否清楚
    【超详细教程】使用Windows Live Writer 2012和Office Word 2013 发布文章到博客园全面总结,再也不愁发博客了
  • 原文地址:https://www.cnblogs.com/hebao0514/p/4851544.html
Copyright © 2020-2023  润新知