zoukankan      html  css  js  c++  java
  • 迭代集合的方式

    1)对list和set集合的迭代
                1》通过iterator迭代
                    Iterator<Integer> it = set.iterator();
                    while (it.hasNext()) {
                        Integer key = it.next();
                        System.out.println(key + "	");
                    }
                2》通过forEach循环
                        for (String name : list) {
                            System.out.print(name + '	');
                        }
                        System.out.println("");
            2)对Map集合迭代
                1》通过keySet()方法
                    Set<Integer> set = map.keySet();
                    Iterator<Integer> it = set.iterator();
                    while (it.hasNext()) {
                        Integer key = it.next();
                        String value = map.get(key);
                        System.out.println(key + " - " + value);
                    }
                    
                2》通过entrySet()方法
                    Set<Entry<Integer, String>> set = map.entrySet();
                    Iterator<Entry<Integer, String>> it = set.iterator();
            
                    while (it.hasNext()) {
                        Entry<Integer, String> en = it.next();
                        Integer key = en.getKey();
                        String value = en.getValue();
                        System.out.println(key + "< - >" + value);
                    }
            
            
        五】迭代细节:【重点】
            在迭代集合时候,一定要动态通知Iterator,而不要动态通知List集合,应选用ListIterator.
            eg:
                System.out.println("list前长度:" + list.size());//3
            
                ListIterator<String> it = list.listIterator();
                while(it.hasNext()){
                    String key = it.next();
                    System.out.print(key+'	');//jack    marry    sisi
                    //动态通知迭代器,加入了新元素,从而迭代器自动通知list集合
                    it.add("qq");
                }
                System.out.println("
    list后长度:"+list.size());//6
                
                
                it = list.listIterator();
                while(it.hasNext()){
                    String key = it.next();
                    System.out.print(key+'	');//jack    qq    marry    qq    sisi    qq
                }
                System.out.println("
    list后长度:"+list.size());//6
    
     
  • 相关阅读:
    spring core源码解读之ASM4用户手册翻译之一asm简介
    nginx启动,重启,关闭命令
    linux LVM分区查看dm设备
    jdbc 对sqlite的基本操作
    linux配置多个ip
    细说Linux下的虚拟主机那些事儿
    打造字符界面的多媒体Linux系统
    linux计划crontab
    因修改/etc/ssh权限导致的ssh不能连接异常解决方法
    Linux修改主机名
  • 原文地址:https://www.cnblogs.com/SkyGood/p/3953410.html
Copyright © 2011-2022 走看看