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 }
  • 相关阅读:
    阿里云 k8s 部署 Spring Cloud Alibaba 微服务实践 (四) 自动化部署
    阿里云 k8s 部署 Spring Cloud Alibaba 微服务实践 (三) 服务观测
    阿里云 k8s 部署 Spring Cloud Alibaba 微服务实践 (二) 部署微服务程序
    阿里云 k8s 部署 Spring Cloud Alibaba 微服务实践 (一) 部署 Nacos
    C++知识点
    libmkl 学习笔记
    基于tesseract-OCR进行中文识别
    poco编译与运行
    Linux下的I/O复用与epoll详解(转载)
    高并发网络编程之epoll详解(转载)
  • 原文地址:https://www.cnblogs.com/hebao0514/p/4851544.html
Copyright © 2011-2022 走看看