zoukankan      html  css  js  c++  java
  • keyset与entryset

    1、基本概述

    Set<Map.Entry<K,V>> entrySet()  返回此映射中包括的映射关系的 set 视图。

    Set<K>              keySet()      返回此映射中包括的键的 set 视图。

    2、效率分析

    对于keySet事实上是遍历了2次,一次是转为iterator,一次就从hashmap中取出key所对于的value。而entryset仅仅是遍历了第一次,他把key和value都放到了entry中,所以就快了。

    3、使用举例

    Map<String, String> maps = new HashMap<String, String>();  
      //方法一: 用entrySet()  
      Iterator<Entry<String,String>> it = maps.entrySet().iterator();  
      while(it.hasNext()){  
       Map.Entry<String,String> m = it.next();  
       String key = m.getKey();
       String value= m.getValue();
      }  
      // 方法二:jdk1.5支持,用entrySet()和For-Each循环()  
      for (Map.Entry<String, String> m : maps.entrySet()) {  
       String key = m.getKey();
       String value= m.getValue();   
      }  
      // 方法三:用keySet()  
      Iterator<String> it2 = maps.keySet().iterator();  
      while (it2.hasNext()){  
       String key = it2.next();
       String value= maps.get(key);
      }  
      // 方法四:jdk1.5支持,用keySet()和For-Each循环  
      for(String m: maps.keySet()){  
       String key = m;
       String value= maps.get(m);
      }

    foreach和while的效率差点儿是差点儿相同的,而for则相对较慢一些。foreach能够替代掉for吗?显然不是。
    foreach的内部原理事实上还是 Iterator,但它不能像Iterator一样能够人为的控制,并且也不能调用iterator.remove(),更不能使用下标来方便的訪问元素。因此foreach这样的循环一般仅仅适合做数组的遍历,提取数据显示等,不适合用于添加删除和使用下标等复杂的操作。

  • 相关阅读:
    python-历史
    10-函数命名空间,作用域,嵌套,闭包
    centos7 搭建dns服务器
    centos7 搭建dhcp服务器
    Nginx 启用 gzip 压缩
    Eclipse 个人手册
    Nginx 命令
    定时任务
    系统设计
    根据 xsd 生成 jaxb java 类
  • 原文地址:https://www.cnblogs.com/blfshiye/p/4356046.html
Copyright © 2011-2022 走看看