编程语言一个简单的例子带你理解HashMap

    作者:邵磊更新于: 2020-04-08 22:44:00

    大神带你学编程,欢迎选课

    一个简单的例子带你理解HashMap。在过去的几十年间,大量的编程语言被发明、被取代、被修改或组合在一起。尽管人们多次试图创造一种通用的程序设计语言,却没有一次尝试是成功的。之所以有那么多种不同的编程语言存在的原因是,编写程序的初衷其实也各不相同;新手与老手之间技术的差距非常大,而且有许多语言对新手来说太难学;还有,不同程序之间的运行成本(runtime cost)各不相同。

    前言

    我知道大家都很熟悉hashmap,并且有事没事都会new一个,但是hashmap的一些特性大家都是看了忘,忘了再记,今天这个例子可以帮助大家很好的记住。

    场景

    用户提交一张试卷答案到服务端,post报文可精简为

    1. [{"question_id":"100001","answer":"A"},  
    2. {"question_id":"100002","answer":"A"},  
    3. {"question_id":"100003","answer":"A"},  
    4. {"question_id":"100004","answer":"A"}] 

    提交地址采用restful风格

    1. http://localhost:8080/exam/{试卷id}/answer 

    那么如何比对客户端传过来的题目就是这张试卷里的呢,假设用户伪造了试卷怎么办?

    正常解决思路

    •  得到试卷所有题目id的list
    •  2层for循环比对题号和答案
    •  判定分数

    大概代码如下

    1. //读取post题目  
    2. for (MexamTestpaperQuestion mexamTestpaperQuestion : mexamTestpaperQuestions) {  
    3.     //通过考试试卷读取题目选项对象  
    4.     MexamQuestionOption questionOption = mexamQuestionDao.findById(mexamTestpaperQuestion.getQuestionId());  
    5.           map1.put("questionid", mexamTestpaperQuestion.getQuestionId());  
    6.           map1.put("answer", mexamQuestionDao.findById(mexamTestpaperQuestion.getQuestionId()).getAnswer());  
    7.           questionAnswerList.add(map1);  
    8.           //将每题分add到一个List  
    9. }  
    10. //遍历试卷内所有题目  
    11. for (Map<String, Object> stringObjectMap : list) {  
    12.     //生成每题结果对象  
    13.     mexamAnswerInfo = new MexamAnswerInfo();  
    14.     mexamAnswerInfo.setAnswerId(answerId);  
    15.     mexamAnswerInfo.setId(id);  
    16.     mexamAnswerInfo.setQuestionId(questionid);  
    17.     mexamAnswerInfo.setResult(anwser);  
    18.     for (Map<String, Object> objectMap : questionAnswerList) {  
    19.         if (objectMap.get("questionid").equals(questionid)) {  
    20.             //比较答案  
    21.             if (anwser.equals(objectMap.get("answer"))) {  
    22.                 totalScore += questionOption.getScore();  
    23.                 mexamAnswerInfo.setIsfalse(true);  
    24.             } else {  
    25.                 mexamAnswerInfo.setIsfalse(false);  
    26.             } 
    27.         }  
    28.     }  
    29.     mexamAnswerInfoDao.addEntity(mexamAnswerInfo);  

    使用普通的2层for循环解决了这个问题,一层是数据库里的题目,一层是用户提交的题目,这时候bug就会暴露出来,假设用户伪造了1万道题目或更多,服务端运算量将增大很多。聊聊 HashMap 和 TreeMap 的内部结构

    利用hashmap来解决

    首先,看看它的定义

    基于哈希表的 Map 接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。(除了不同步和允许使用 null 之外,HashMap 类与 Hashtable 大致相同。)此类不保证映射的顺序,特别是它不保证该顺序恒久不变。

    主要看HashMap k-v均支持空值,我们何不将用户提交了答案add到一个HashMap里,其中题目id作为key,答案作为value,而且HashMap的key支持以字母开头。

    我们只需要for循环试卷所有题目,然后通过这个map.put("题目id")就能得到答案,然后比较答案即可,因为HashMap的key是基于hashcode的形式存储的,所以在程序中该方案效率很高。

    思路:

    •  将提交答案以questionid为key,answer为value加入一个hashmap
    •  for循环实体列表,直接比对答案
    •  判分

    代码如下:     

    1. //拿到用户提交的数据  
    2.        Map<String, String> resultMap = new HashMap<>();  
    3.        JSONArray questions = JSON.parseArray(params.get("questions").toString());  
    4.        for (int size = questions.size(); size > 0; size--) {  
    5.            JSONObject question = (JSONObject) questions.get(size - 1);  
    6.            resultMap.put(question.getString("questionid"), question.getString("answer")); 
    7.        }  
    8.        //拿到试卷下的所有试题  
    9.        List<MexamTestpaperQuestion> mexamTestpaperQuestions = mexamTestpaperQuestionDao.findBy(map);  
    10.        int totalScore = 0;  
    11.        for (MexamTestpaperQuestion mexamTestpaperQuestion : mexamTestpaperQuestions) {  
    12.            MexamQuestionOption questionOption = mexamQuestionDao.findById(mexamTestpaperQuestion.getQuestionId());  
    13.            MexamAnswerInfo mexamAnswerInfo = new MexamAnswerInfo(); 
    14.             mexamAnswerInfo.setAnswerId(answerId);  
    15.            mexamAnswerInfo.setId(id);  
    16.            mexamAnswerInfo.setQuestionId(questionOption.getId());  
    17.            mexamAnswerInfo.setResult(resultMap.get(questionOption.getId()));  
    18.            //拿到试卷的id作为resultMap的key去查,能查到就有这个题目,然后比对answer,进行存储  
    19.            if (questionOption.getAnswer().equals(resultMap.get(questionOption.getId()))) {  
    20.                mexamAnswerInfo.setIsfalse(true);  
    21.                totalScore += questionOption.getScore();  
    22.            } else {  
    23.                mexamAnswerInfo.setIsfalse(false);  
    24.            }  
    25.            mexamAnswerInfoDao.addEntity(mexamAnswerInfo);  
    26.        } 

    分析HashMap

    先看看文档

    编程语言一个简单的例子带你理解HashMap_编程语言_程序员_计算机_课课家

    大概翻译为如下几点

    •  实现Map ,可克隆,可序列化
    •  基于哈希表的Map接口实现。
    •  此实现提供所有可选的映射操作,并允许 空值和空键。(HashMap 类大致相当于Hashtable,除非它是不同步的,并且允许null)。这个类不能保证Map的顺序; 特别是不能保证订单在一段时间内保持不变。
    •  这个实现为基本操作(get和put)提供了恒定时间的性能,假设散列函数在这些存储桶之间正确分散元素。集合视图的迭代需要与HashMap实例的“容量” (桶数)及其大小(键值映射数)成正比 。因此,如果迭代性能很重要,不要将初始容量设置得太高(或负载因子太低)是非常重要的。
    •  HashMap的一个实例有两个影响其性能的参数:初始容量和负载因子。容量是在哈希表中桶的数量,和初始容量是简单地在创建哈希表中的时间的能力。该 负载系数是的哈希表是如何充分允许获得之前它的容量自动增加的措施。当在散列表中的条目的数量超过了负载因数和电流容量的乘积,哈希表被重新散列(即,内部数据结构被重建),使得哈希表具有桶的大约两倍。

    那么put逻辑是怎么样的呢?

    HashMap的key在put时,并不需要挨个使用equals比较,那样时间复杂度O(n),也就说HashMap内有多少元素就需要循环多少次。

    而HashMap是将key转为hashcode,关于hashcode的确可能存在多个string相同的hashcode,但是最终HashMap还会比较一次bucketIndex。bucketIndex是HashMap存储k-v的位置,时间复杂度只有O(1)。

    图解

    源码

    1. /**  
    2.    * Associates the specified value with the specified key in this map.  
    3.    * If the map previously contained a mapping for the key, the old  
    4.    * value is replaced. 
    5.    *  
    6.    * @param key key with which the specified value is to be associated  
    7.    * @param value value to be associated with the specified key  
    8.    * @return the previous value associated with <tt>keytt>, or  
    9.    *         <tt>nulltt> if there was no mapping for <tt>keytt>.  
    10.    *         (A <tt>nulltt> return can also indicate that the map  
    11.    *         previously associated <tt>nulltt> with <tt>keytt>.)  
    12.    */  
    13.   public V put(K key, V value) {  
    14.       // 以key的哈希码作为key    
    15.       return putVal(hash(key), key, value, false, true);  
    16.   }  
    17.   /**  
    18.    * Implements Map.put and related methods  
    19.    *  
    20.    * @param hash hash for key  
    21.    * @param key the key  
    22.    * @param value the value to put  
    23.    * @param onlyIfAbsent if true, don't change existing value  
    24.    * @param evict if false, the table is in creation mode.  
    25.    * @return previous value, or null if none  
    26.    */  
    27.   final V putVal(int hash, K key, V value, boolean onlyIfAbsent,  
    28.                  boolean evict) {  
    29.       Node<K,V>[] tab; Node<K,V> p; int n, i;  
    30.       // 处理key为null,HashMap允许key和value为null   
    31.       if ((tab = table) == null || (n = tab.length) == 0)  
    32.           n = (tab = resize()).length;  
    33.       if ((p = tab[i = (n - 1) & hash]) == null)  
    34.           tab[i] = newNode(hash, key, value, null);  
    35.       else {  
    36.           Node<K,V> e; K k;  
    37.           if (p.hash == hash &&  
    38.               ((k = p.key) == key || (key != null && key.equals(k))))  
    39.               e = p;  
    40.           else if (p instanceof TreeNode)  
    41.               //以树形结构存储 
    42.                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);  
    43.           else {  
    44.               //以链表形式存储  
    45.               for (int binCount = 0; ; ++binCount) {  
    46.                   if ((e = p.next) == null) {  
    47.                       p.next = newNode(hash, key, value, null);  
    48.                       if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st  
    49.                           treeifyBin(tab, hash);  
    50.                       break;  
    51.                   }  
    52.                   if (e.hash == hash &&  
    53.                       ((k = e.key) == key || (key != null && key.equals(k))))  
    54.                       break;  
    55.                   p = e;  
    56.               }  
    57.           }  
    58.           //如果是key已存在则修改旧值,并返回旧值  
    59.           if (e != null) { // existing mapping for key  
    60.               V oldValue = e.value;  
    61.               if (!onlyIfAbsent || oldValue == null)  
    62.                   e.value = value;  
    63.               afterNodeAccess(e);  
    64.               return oldValue;  
    65.           }  
    66.       }  
    67.       ++modCount;  
    68.       if (++size > threshold)  
    69.           resize();  
    70.       //如果key不存在,则执行插入操作,返回null。 
    71.       afterNodeInsertion(evict);  
    72.       return null;  
    73.   } 

    put方法分两种情况:bucket是以链表形式存储的还是以树形结构存储的。如果是key已存在则修改旧值,并返回旧值。如果key不存在,则执行插入操作,返回null。put操作,当发生碰撞时,如果是使用链表处理冲突,则执行的尾插法。

    put操作的大概流程:

    •  通过hash值得到所在bucket的下标,如果为null,表示没有发生碰撞,则直接put
    •  如果发生了碰撞,则解决发生碰撞的实现方式:链表还是树。
    •  如果能够找到该key的结点,则执行更新操作。
    •  如果没有找到该key的结点,则执行插入操作,需要对modCount++。
    •  在执行插入操作之后,如果size超过了threshold,这要扩容执行resize()。
      高级语言的出现使得计算机程序设计语言不再过度地依赖某种特定的机器或环境。这是因为高级语言在不同的平台上会被编译成不同的机器语言,而不是直接被机器执行。最早出现的编程语言之一FORTRAN的一个主要目标,就是实现平台独立。

课课家教育

未登录