zoukankan      html  css  js  c++  java
  • Java集合——集合框架Iterator接口

    1.集合输出

    很多情况下我们需要把集合的内容进行输出,也就是遍历集合。

    遍历集合的方式有以下几种:

    1.Iterator

    2.ListIterator

    3.Enumeration(枚举方式,比较老一般不用)

    4.foreach

    5.传统for循环

    其中Iterator的使用率最高。

    public class CollectionIterator {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO 自动生成的方法存根
            iterator();
            fors();
            foreach();
        }
        /**
         * 使用Iterator迭代
         */
        public static void iterator(){
            List<Student> list=new ArrayList<Student>();
            Student stu1=new Student("小刚",16);
            Student stu2=new Student("小花",23);
            Student stu3=new Student("小刚",16);
            list.add(stu1);
            list.add(stu2);
            list.add(stu3);
            Iterator<Student> i=list.iterator();
            while(i.hasNext()){
                System.out.println(i.next());
            }
        }
        /**
         * 使用for循环迭代
         * 针对数组集合来说,使用传统的for遍历效率更高
         */
        public static void fors(){
            List<Student> list=new ArrayList<Student>();
            Student stu1=new Student("小刚",16);
            Student stu2=new Student("小花",23);
            Student stu3=new Student("小刚",16);
            list.add(stu1);
            list.add(stu2);
            list.add(stu3);
            //使用Iterator迭代
            int size=list.size();
            for(int i=0;i<size;i++){
                System.out.println(list.get(i));
            }
        }
        /**
         * 使用foreach迭代
         */
        public static void foreach(){
            List<Student> list=new ArrayList<Student>();
            Student stu1=new Student("小刚",16);
            Student stu2=new Student("小花",23);
            Student stu3=new Student("小刚",16);
            list.add(stu1);
            list.add(stu2);
            list.add(stu3);
            for(Student s:list){
                System.out.println(s);
            }
        }
        
    }
  • 相关阅读:
    数据库表结构变动发邮件脚本
    .net程序打包部署
    无法登陆GitHub解决方法
    netbeans 打包生成 jar
    第一次值班
    RHEL6 纯命令行文本界面下安装桌面
    C语言中格式化输出,四舍五入类型问题
    I'm up to my ears
    How to boot ubuntu in text mode instead of graphical(X) mode
    the IP routing table under linux@school
  • 原文地址:https://www.cnblogs.com/shenhainixin/p/5129424.html
Copyright © 2011-2022 走看看