• for 迭代器遍历list map


    1、map与list区别

        list是对象集合,允许对象重复。

        map是键值对的集合,不允许key重复

    2、list 与 list<类型>

        list不限制类型,也就是object类型

        list<类型>限定在某一类型,使用时不需要强转,避免运行错误

        注:map 与 map<key ,value>也是同样的

    Demo1:遍历list list<类型>

    List list=new ArrayList();
            list.add("123");
            list.add(456);
            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i));
            }
             
            Iterator it=list.iterator();//迭代器
            while (it.hasNext()) {
                 
                System.out.println(it.next());
                 
            }
             
            List<String> list2=new ArrayList<String>();
            list2.add("123");
            list2.add("rwrew");
            for (int i = 0; i < list2.size(); i++) {
                System.out.println(list2.get(i));
            }
            Iterator<String> it1= list2.iterator();//使用迭代器输出
            while (it1.hasNext()) {
                System.out.println(it1.next());
                 
            }

    Demo2:遍历map<key,value>

    Map<Integer, String> map=new HashMap<Integer, String>();
            map.put(1,"壹");
            map.put(2,"贰");
            //方法1:用for循环输出
            for (String datakey:map.values()) //map.keySet()  获得所有的键值key   map.values() 获得所有的values值
            {
                System.out.println(datakey);
            }
            //方法2:用迭代器输出
            Set<Entry<Integer, String>> set= map.entrySet();//转化为set
            Iterator<Entry<Integer, String>> iterator =set.iterator();//迭代器
            while (iterator.hasNext()) {//循环输出
             Entry<Integer, String> entry=    iterator.next();
             Integer key=entry.getKey();//key
             String value=entry.getValue();//value
             System.out.println(key +" : "+ value);
              
                 
            }
  • 相关阅读:
    ES6变量的解构赋值
    ES6新增内容
    Rvalue references
    range-based for statement
    Space in Template Expression, nullptr, and auto
    Type Alias、noexcept、override、final
    Variadic Template
    =default =delete
    为什么不要特化函数模版?
    boost::noncopyable 的作用
  • 原文地址:https://www.cnblogs.com/liuwt365/p/4079400.html
Copyright © 2020-2023  润新知