• 关于Dictionary元素的遍历


    以前我面试别人的时候,我经常会问应聘者,如何在C#中遍历Hashtable中的元素,每次遍历时,需要得到Key和Value。

    一直以来,也经常有人问这个问题。包括Java下Map的元素的遍历。我在水木清华的Java版也回答过这个问题。

    .NET平台下:
    IDictionary dictionary = new Hashtable();
    foreach (DictionaryEntry entry in dictionary)
    {
        Object key 
    = entry.Key;
        Object val 
    = entry.Value;
    }

    Java环境下:
    Map map = new HashMap();
    Iterator iter 
    = map.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry entry 
    = (Map.Entry) iter.next();
        Object key 
    = entry.getKey();
        Object val 
    = entry.getValue();
    }

    点评:
    .NET环境下,引入了foreach的写法,但是IDictionary和ICollection的GetEnumerator()方法返回的类型是不一样的,这一点,很容易让人迷惑,初学者很多都会写错。如下是初学者常用的写法:
    IDictionary dictionary = new Hashtable();
    foreach (Object val in dictionary)
    {
        
    //
    }
    这是一个地雷,.NET的基础类库和C#在语言的设计(对foreach的支持方式)的相互作用下,产生了这一个地雷,也许也可以称之为缺陷……

    Java下,使用起来的方式,有点麻烦,很多初学者,不使用恰当的方法遍历Map,甚至一些写了多年Java程序员都是用比较笨的办法。
    Map map = new HashMap();
    Iterator iter 
    = map.keySet().iterator();
    while (iter.hasNext()) {
        Object key 
    = iter.next();
        Object val 
    = map.get(key);
    }
    这种方式效率会比较低。

  • 相关阅读:
    vue父子组件通信
    canvas(一)
    js中的this
    git中遇到的问题
    javaScript中各种数据结构的遍历
    git合并多个提交
    vue学习笔记(三)——vuex—store配置
    vue学习笔记(二)——路由配置
    0欧电阻的作用
    STM32L系列单片机内部EEPROM的读写
  • 原文地址:https://www.cnblogs.com/jobs/p/24942.html
Copyright © 2020-2023  润新知