zoukankan      html  css  js  c++  java
  • 增强型for和Iterator学习

    1,增强for和对于非集合类(没有实现 Iterable接口)的数组遍历效果一样

    2,对于集合类,就是隐式调用迭代器 iterator的遍历,各有各个场合

    3,对于arraylist来所,由于数据结构是数据,可以获得get的索引,反而用普通循环速度更快。linkedlist这种基于链表的数据结构,就用增强for速度比较快

     List<String> list = new ArrayList<String>();
            for (int i = 0; i < 500000; i++) {
                list.add("xiaotang");
            }
     
            long start = System.currentTimeMillis();
            int size = list.size();
            String str = null;
            for (int i = 0; i < size; i++) {
                str = list.get(i);
            }
            System.out.println("for + get(i)方法: "
                    + (System.currentTimeMillis() - start));
     
            long start2 = System.currentTimeMillis();
            for (String str1 : list) {
            }
            System.out.println("Iterator(foreach)方法:"
                    + (System.currentTimeMillis() - start2));
    View Code
       Iterator<Integer> itr = lst.iterator(); 
            while (itr.hasNext()) 
                if (itr.next() % 2 == 0) 
                    itr.remove(); 
    add/get/remove

    4,增强for获得实例,不能再循环中删除,否则有异常,原理:foreach引用了iterator,调用hasnext和next方法,在外面remove会改变iterator的expectModeCount和list的modcount不同步),

    iterator就有remove方法直接删除(expectCount会自动同步),要想添加就要用原始的for,或者迭代器的删了再加,保存平衡,foreach尽量只读

    参考:https://my.oschina.net/itblog/blog/422649

    以下例子证明第一点 
    ①     public static void removeEvensVer2(List<Integer> lst) 
        { 
            for (Integer x : lst) 
                if (x % 2 == 0) 
                    lst.remove(x); 
            
            System.out.println(lst); 
        } 
    
    ②     public static void removeEvensVer3(List<Integer> lst) 
        { 
            Iterator<Integer> itr = lst.iterator(); 
            while (itr.hasNext()) 
                if (itr.next() % 2 == 0) 
                    itr.remove(); 
         
            System.out.println(lst); 
        } 
    View Code

    5,map有4种方法,1,map.entrySet(),2,map.keySet()和map.values(),3,Iterator,4,通过keySet来便利

    总结:键值都有用1,仅仅键或者值用2,删除用iterator

    参考,https://www.cnblogs.com/lchzls/p/6714689.html

    真正的:https://blog.csdn.net/tjcyjd/article/details/11111401

  • 相关阅读:
    shell 学习笔记4-shell内置变量命令
    shell 学习笔记3-shell变量扩展
    vmware vSphere Data Protection 6.1 --------3-使用备份、恢复、报告
    shell 学习笔记2-shell-test
    vmware vSphere Data Protection 6.1--------2-初始化
    Centos7+puppet+foreman,模板介绍
    vmware vSphere Data Protection 6.1 --------1-部署
    vmware vcsa-故障1
    Grafana重置admin登录密码
    MongoDB远程连接报错
  • 原文地址:https://www.cnblogs.com/vhyc/p/9363652.html
Copyright © 2011-2022 走看看