zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    nacos 配置优先级
    spring cloud 依赖查询
    树-数据结构
    CI/CD + docker 综合实战
    CICD:CentOS 下 Jenkins 安装
    生产环境 OOM 与 GC 问题的处理思路
    如何优雅的进行接口管理
    合并多个Execl 电子表格 java poi
    深入了解数据导入的一些解决方案
    浅谈导出Execl的报表数据解决方案
  • 原文地址:https://www.cnblogs.com/hebao0514/p/4851544.html
Copyright © 2011-2022 走看看