自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

一個簡單的例子帶你理解HashMap

開發(fā) 后端
我知道大家都很熟悉hashmap,并且有事沒事都會new一個,但是hashmap的一些特性大家都是看了忘,忘了再記,今天這個例子可以幫助大家很好的記住。

前言

我知道大家都很熟悉hashmap,并且有事沒事都會new一個,但是hashmap的一些特性大家都是看了忘,忘了再記,今天這個例子可以幫助大家很好的記住。

場景

用戶提交一張試卷答案到服務(wù)端,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風(fēng)格 

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

那么如何比對客戶端傳過來的題目就是這張試卷里的呢,假設(shè)用戶偽造了試卷怎么辦?

正常解決思路

  •  得到試卷所有題目id的list
  •  2層for循環(huán)比對題號和答案
  •  判定分數(shù)

大概代碼如下 

  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. //遍歷試卷內(nèi)所有題目  
  11. for (Map<String, Object> stringObjectMap : list) {  
  12.     //生成每題結(jié)果對象  
  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循環(huán)解決了這個問題,一層是數(shù)據(jù)庫里的題目,一層是用戶提交的題目,這時候bug就會暴露出來,假設(shè)用戶偽造了1萬道題目或更多,服務(wù)端運算量將增大很多。聊聊 HashMap 和 TreeMap 的內(nèi)部結(jié)構(gòu)

利用hashmap來解決

首先,看看它的定義

基于哈希表的 Map 接口的實現(xiàn)。此實現(xiàn)提供所有可選的映射操作,并允許使用 null 值和 null 鍵。(除了不同步和允許使用 null 之外,HashMap 類與 Hashtable 大致相同。)此類不保證映射的順序,特別是它不保證該順序恒久不變。

主要看HashMap k-v均支持空值,我們何不將用戶提交了答案add到一個HashMap里,其中題目id作為key,答案作為value,而且HashMap的key支持以字母開頭。

我們只需要for循環(huán)試卷所有題目,然后通過這個map.put("題目id")就能得到答案,然后比較答案即可,因為HashMap的key是基于hashcode的形式存儲的,所以在程序中該方案效率很高。

思路:

  •  將提交答案以questionid為key,answer為value加入一個hashmap
  •  for循環(huán)實體列表,直接比對答案
  •  判分

代碼如下:       

  1. //拿到用戶提交的數(shù)據(jù)  
  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

先看看文檔

大概翻譯為如下幾點

  •  實現(xiàn)Map ,可克隆,可序列化
  •  基于哈希表的Map接口實現(xiàn)。
  •  此實現(xiàn)提供所有可選的映射操作,并允許 空值和空鍵。(HashMap 類大致相當于Hashtable,除非它是不同步的,并且允許null)。這個類不能保證Map的順序; 特別是不能保證訂單在一段時間內(nèi)保持不變。
  •  這個實現(xiàn)為基本操作(get和put)提供了恒定時間的性能,假設(shè)散列函數(shù)在這些存儲桶之間正確分散元素。集合視圖的迭代需要與HashMap實例的“容量” (桶數(shù))及其大?。ㄦI值映射數(shù))成正比 。因此,如果迭代性能很重要,不要將初始容量設(shè)置得太高(或負載因子太低)是非常重要的。
  •  HashMap的一個實例有兩個影響其性能的參數(shù):初始容量和負載因子。容量是在哈希表中桶的數(shù)量,和初始容量是簡單地在創(chuàng)建哈希表中的時間的能力。該 負載系數(shù)是的哈希表是如何充分允許獲得之前它的容量自動增加的措施。當在散列表中的條目的數(shù)量超過了負載因數(shù)和電流容量的乘積,哈希表被重新散列(即,內(nèi)部數(shù)據(jù)結(jié)構(gòu)被重建),使得哈希表具有桶的大約兩倍。

那么put邏輯是怎么樣的呢?

HashMap的key在put時,并不需要挨個使用equals比較,那樣時間復(fù)雜度O(n),也就說HashMap內(nèi)有多少元素就需要循環(huán)多少次。 

而HashMap是將key轉(zhuǎn)為hashcode,關(guān)于hashcode的確可能存在多個string相同的hashcode,但是最終HashMap還會比較一次bucketIndex。bucketIndex是HashMap存儲k-v的位置,時間復(fù)雜度只有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>key</tt>, or  
  9.    *         <tt>null</tt> if there was no mapping for <tt>key</tt> 
  10.    *         (A <tt>null</tt> return can also indicate that the map  
  11.    *         previously associated <tt>null</tt> with <tt>key</tt>.)  
  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.               //以樹形結(jié)構(gòu)存儲 
  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不存在,則執(zhí)行插入操作,返回null。 
  71.       afterNodeInsertion(evict);  
  72.       return null;  
  73.   } 

put方法分兩種情況:bucket是以鏈表形式存儲的還是以樹形結(jié)構(gòu)存儲的。如果是key已存在則修改舊值,并返回舊值。如果key不存在,則執(zhí)行插入操作,返回null。put操作,當發(fā)生碰撞時,如果是使用鏈表處理沖突,則執(zhí)行的尾插法。

put操作的大概流程:

  •  通過hash值得到所在bucket的下標,如果為null,表示沒有發(fā)生碰撞,則直接put
  •  如果發(fā)生了碰撞,則解決發(fā)生碰撞的實現(xiàn)方式:鏈表還是樹。
  •  如果能夠找到該key的結(jié)點,則執(zhí)行更新操作。
  •  如果沒有找到該key的結(jié)點,則執(zhí)行插入操作,需要對modCount++。
  •  在執(zhí)行插入操作之后,如果size超過了threshold,這要擴容執(zhí)行resize()。 

 

責(zé)任編輯:龐桂玉 來源: Java知音
相關(guān)推薦

2019-11-13 15:14:31

MySQL事務(wù)數(shù)據(jù)庫

2009-07-14 16:02:42

JDBC例子

2010-04-19 17:21:36

Oracle寫文件

2011-08-02 12:46:46

Oracle數(shù)據(jù)表建立索引

2021-11-05 07:59:25

HashMapJava知識總結(jié)

2023-11-06 13:55:59

聯(lián)合索引MySQ

2011-03-24 09:34:41

SPRING

2011-05-06 14:19:29

ExcelSQL Server

2020-10-26 13:12:00

多線程調(diào)度隨機性

2021-07-09 06:11:37

Java泛型Object類型

2022-10-19 11:31:49

TDD開發(fā)

2009-08-26 15:53:42

C#數(shù)據(jù)訪問XML

2009-08-19 04:14:00

線性鏈表

2018-11-22 14:09:45

iOS架構(gòu)組件開發(fā)

2023-02-07 10:40:30

gRPC系統(tǒng)Mac

2020-11-09 06:38:00

ninja構(gòu)建方式構(gòu)建系統(tǒng)

2020-06-23 10:03:33

版本控制項目

2017-04-26 14:48:01

Chrome程序擴展

2021-09-07 07:34:42

CSS 技巧代碼重構(gòu)

2009-07-21 14:55:30

點贊
收藏

51CTO技術(shù)棧公眾號