<output id="qn6qe"></output>

    1. <output id="qn6qe"><tt id="qn6qe"></tt></output>
    2. <strike id="qn6qe"></strike>

      亚洲 日本 欧洲 欧美 视频,日韩中文字幕有码av,一本一道av中文字幕无码,国产线播放免费人成视频播放,人妻少妇偷人无码视频,日夜啪啪一区二区三区,国产尤物精品自在拍视频首页,久热这里只有精品12

      hashmap實(shí)現(xiàn)原理淺析

      看了下JAVA里面有HashMap、Hashtable、HashSet三種hash集合的實(shí)現(xiàn)源碼,這里總結(jié)下,理解錯(cuò)誤的地方還望指正

      HashMap和Hashtable的區(qū)別

      HashSet和HashMap、Hashtable的區(qū)別

      HashMap和Hashtable的實(shí)現(xiàn)原理

      HashMap的簡(jiǎn)化實(shí)現(xiàn)MyHashMap

       

      HashMap和Hashtable的區(qū)別

      1. 兩者最主要的區(qū)別在于Hashtable是線程安全,而HashMap則非線程安全
        Hashtable的實(shí)現(xiàn)方法里面都添加了synchronized關(guān)鍵字來確保線程同步,因此相對(duì)而言HashMap性能會(huì)高一些,我們平時(shí)使用時(shí)若無特殊需求建議使用HashMap,在多線程環(huán)境下若使用HashMap需要使用Collections.synchronizedMap()方法來獲取一個(gè)線程安全的集合(Collections.synchronizedMap()實(shí)現(xiàn)原理是Collections定義了一個(gè)SynchronizedMap的內(nèi)部類,這個(gè)類實(shí)現(xiàn)了Map接口,在調(diào)用方法時(shí)使用synchronized來保證線程同步,當(dāng)然了實(shí)際上操作的還是我們傳入的HashMap實(shí)例,簡(jiǎn)單的說就是Collections.synchronizedMap()方法幫我們?cè)诓僮鱄ashMap時(shí)自動(dòng)添加了synchronized來實(shí)現(xiàn)線程同步,類似的其它Collections.synchronizedXX方法也是類似原理
      2. HashMap可以使用null作為key,而Hashtable則不允許null作為key
        雖說HashMap支持null值作為key,不過建議還是盡量避免這樣使用,因?yàn)橐坏┎恍⌒氖褂昧耍粢虼艘l(fā)一些問題,排查起來很是費(fèi)事
        HashMap以null作為key時(shí),總是存儲(chǔ)在table數(shù)組的第一個(gè)節(jié)點(diǎn)上
      3. HashMap是對(duì)Map接口的實(shí)現(xiàn),HashTable實(shí)現(xiàn)了Map接口和Dictionary抽象類
      4. HashMap的初始容量為16,Hashtable初始容量為11,兩者的填充因子默認(rèn)都是0.75
        HashMap擴(kuò)容時(shí)是當(dāng)前容量翻倍即:capacity*2,Hashtable擴(kuò)容時(shí)是容量翻倍+1即:capacity*2+1
      5. 兩者計(jì)算hash的方法不同
        Hashtable計(jì)算hash是直接使用key的hashcode對(duì)table數(shù)組的長(zhǎng)度直接進(jìn)行取模
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;

        HashMap計(jì)算hash對(duì)key的hashcode進(jìn)行了二次hash,以獲得更好的散列值,然后對(duì)table數(shù)組長(zhǎng)度取摸

        static int hash(int h) {
                // This function ensures that hashCodes that differ only by
                // constant multiples at each bit position have a bounded
                // number of collisions (approximately 8 at default load factor).
                h ^= (h >>> 20) ^ (h >>> 12);
                return h ^ (h >>> 7) ^ (h >>> 4);
            }
        
         static int indexFor(int h, int length) {
                return h & (length-1);
            }

         

      6. HashMap和Hashtable的底層實(shí)現(xiàn)都是數(shù)組+鏈表結(jié)構(gòu)實(shí)現(xiàn)

      HashSet和HashMap、Hashtable的區(qū)別

      除開HashMap和Hashtable外,還有一個(gè)hash集合HashSet,有所區(qū)別的是HashSet不是key value結(jié)構(gòu),僅僅是存儲(chǔ)不重復(fù)的元素,相當(dāng)于簡(jiǎn)化版的HashMap,只是包含HashMap中的key而已

      通過查看源碼也證實(shí)了這一點(diǎn),HashSet內(nèi)部就是使用HashMap實(shí)現(xiàn),只不過HashSet里面的HashMap所有的value都是同一個(gè)Object而已,因此HashSet也是非線程安全的,至于HashSet和Hashtable的區(qū)別,HashSet就是個(gè)簡(jiǎn)化的HashMap的,所以你懂的
      下面是HashSet幾個(gè)主要方法的實(shí)現(xiàn)

        private transient HashMap<E,Object> map;
      private static final Object PRESENT = new Object();
      public HashSet() { map = new HashMap<E,Object>(); } public boolean contains(Object o) { return map.containsKey(o); } public boolean add(E e) { return map.put(e, PRESENT)==null; } public boolean add(E e) { return map.put(e, PRESENT)==null; } public boolean remove(Object o) { return map.remove(o)==PRESENT; } public void clear() { map.clear(); }

       

      HashMap和Hashtable的實(shí)現(xiàn)原理

      HashMap和Hashtable的底層實(shí)現(xiàn)都是數(shù)組+鏈表結(jié)構(gòu)實(shí)現(xiàn)的,這點(diǎn)上完全一致

      添加、刪除、獲取元素時(shí)都是先計(jì)算hash,根據(jù)hash和table.length計(jì)算index也就是table數(shù)組的下標(biāo),然后進(jìn)行相應(yīng)操作,下面以HashMap為例說明下它的簡(jiǎn)單實(shí)現(xiàn)

        /**
           * HashMap的默認(rèn)初始容量 必須為2的n次冪
           */
          static final int DEFAULT_INITIAL_CAPACITY = 16;
      
          /**
           * HashMap的最大容量,可以認(rèn)為是int的最大值    
           */
          static final int MAXIMUM_CAPACITY = 1 << 30;
      
          /**
           * 默認(rèn)的加載因子
           */
          static final float DEFAULT_LOAD_FACTOR = 0.75f;
      
          /**
           * HashMap用來存儲(chǔ)數(shù)據(jù)的數(shù)組
           */
          transient Entry[] table;
      • HashMap的創(chuàng)建
        HashMap默認(rèn)初始化時(shí)會(huì)創(chuàng)建一個(gè)默認(rèn)容量為16的Entry數(shù)組,默認(rèn)加載因子為0.75,同時(shí)設(shè)置臨界值為16*0.75
            /**
             * Constructs an empty <tt>HashMap</tt> with the default initial capacity
             * (16) and the default load factor (0.75).
             */
            public HashMap() {
                this.loadFactor = DEFAULT_LOAD_FACTOR;
                threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
                table = new Entry[DEFAULT_INITIAL_CAPACITY];
                init();
            }

         

      • put方法
        HashMap會(huì)對(duì)null值key進(jìn)行特殊處理,總是放到table[0]位置
        put過程是先計(jì)算hash然后通過hash與table.length取摸計(jì)算index值,然后將key放到table[index]位置,當(dāng)table[index]已存在其它元素時(shí),會(huì)在table[index]位置形成一個(gè)鏈表,將新添加的元素放在table[index],原來的元素通過Entry的next進(jìn)行鏈接,這樣以鏈表形式解決hash沖突問題,當(dāng)元素?cái)?shù)量達(dá)到臨界值(capactiy*factor)時(shí),則進(jìn)行擴(kuò)容,是table數(shù)組長(zhǎng)度變?yōu)閠able.length*2
      •  public V put(K key, V value) {
                if (key == null)
                    return putForNullKey(value); //處理null值
                int hash = hash(key.hashCode());//計(jì)算hash
                int i = indexFor(hash, table.length);//計(jì)算在數(shù)組中的存儲(chǔ)位置
            //遍歷table[i]位置的鏈表,查找相同的key,若找到則使用新的value替換掉原來的oldValue并返回oldValue
                for (Entry<K,V> e = table[i]; e != null; e = e.next) {
                    Object k;
                    if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                        V oldValue = e.value;
                        e.value = value;
                        e.recordAccess(this);
                        return oldValue;
                    }
                }
            //若沒有在table[i]位置找到相同的key,則添加key到table[i]位置,新的元素總是在table[i]位置的第一個(gè)元素,原來的元素后移
                modCount++;
                addEntry(hash, key, value, i);
                return null;
            }
        
          
            void addEntry(int hash, K key, V value, int bucketIndex) {
            //添加key到table[bucketIndex]位置,新的元素總是在table[bucketIndex]的第一個(gè)元素,原來的元素后移
            Entry<K,V> e = table[bucketIndex];
                table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
            //判斷元素個(gè)數(shù)是否達(dá)到了臨界值,若已達(dá)到臨界值則擴(kuò)容,table長(zhǎng)度翻倍
                if (size++ >= threshold)
                    resize(2 * table.length);
            }

         

      • get方法
        同樣當(dāng)key為null時(shí)會(huì)進(jìn)行特殊處理,在table[0]的鏈表上查找key為null的元素
        get的過程是先計(jì)算hash然后通過hash與table.length取摸計(jì)算index值,然后遍歷table[index]上的鏈表,直到找到key,然后返回
        public V get(Object key) {
                if (key == null)
                    return getForNullKey();//處理null值
                int hash = hash(key.hashCode());//計(jì)算hash
            //在table[index]遍歷查找key,若找到則返回value,找不到返回null
                for (Entry<K,V> e = table[indexFor(hash, table.length)];
                     e != null;
                     e = e.next) {
                    Object k;
                    if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
                        return e.value;
                }
                return null;
            }

         

      • remove方法
        remove方法和put get類似,計(jì)算hash,計(jì)算index,然后遍歷查找,將找到的元素從table[index]鏈表移除
            public V remove(Object key) {
                Entry<K,V> e = removeEntryForKey(key);
                return (e == null ? null : e.value);
            }
            final Entry<K,V> removeEntryForKey(Object key) {
                int hash = (key == null) ? 0 : hash(key.hashCode());
                int i = indexFor(hash, table.length);
                Entry<K,V> prev = table[i];
                Entry<K,V> e = prev;
        
                while (e != null) {
                    Entry<K,V> next = e.next;
                    Object k;
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) {
                        modCount++;
                        size--;
                        if (prev == e)
                            table[i] = next;
                        else
                            prev.next = next;
                        e.recordRemoval(this);
                        return e;
                    }
                    prev = e;
                    e = next;
                }
        
                return e;
            }

         

      • resize方法
        resize方法在hashmap中并沒有公開,這個(gè)方法實(shí)現(xiàn)了非常重要的hashmap擴(kuò)容,具體過程為:先創(chuàng)建一個(gè)容量為table.length*2的新table,修改臨界值,然后把table里面元素計(jì)算hash值并使用hash與table.length*2重新計(jì)算index放入到新的table里面
        這里需要注意下是用每個(gè)元素的hash全部重新計(jì)算index,而不是簡(jiǎn)單的把原table對(duì)應(yīng)index位置元素簡(jiǎn)單的移動(dòng)到新table對(duì)應(yīng)位置
        void resize(int newCapacity) {
                Entry[] oldTable = table;
                int oldCapacity = oldTable.length;
                if (oldCapacity == MAXIMUM_CAPACITY) {
                    threshold = Integer.MAX_VALUE;
                    return;
                }
        
                Entry[] newTable = new Entry[newCapacity];
                transfer(newTable);
                table = newTable;
                threshold = (int)(newCapacity * loadFactor);
            }
        
            void transfer(Entry[] newTable) {
                Entry[] src = table;
                int newCapacity = newTable.length;
                for (int j = 0; j < src.length; j++) {
                    Entry<K,V> e = src[j];
                    if (e != null) {
                        src[j] = null;        
                        do {
                            Entry<K,V> next = e.next;
        //重新對(duì)每個(gè)元素計(jì)算index
        int i = indexFor(e.hash, newCapacity); e.next = newTable[i]; newTable[i] = e; e = next; } while (e != null); } } }

         

      • clear()方法
        clear方法非常簡(jiǎn)單,就是遍歷table然后把每個(gè)位置置為null,同時(shí)修改元素個(gè)數(shù)為0
        需要注意的是clear方法只會(huì)清楚里面的元素,并不會(huì)重置capactiy
         public void clear() {
                modCount++;
                Entry[] tab = table;
                for (int i = 0; i < tab.length; i++)
                    tab[i] = null;
                size = 0;
            }

         

      • containsKey和containsValue
        containsKey方法是先計(jì)算hash然后使用hash和table.length取摸得到index值,遍歷table[index]元素查找是否包含key相同的值
        public boolean containsKey(Object key) {
                return getEntry(key) != null;
            }
        final Entry<K,V> getEntry(Object key) {
                int hash = (key == null) ? 0 : hash(key.hashCode());
                for (Entry<K,V> e = table[indexFor(hash, table.length)];
                     e != null;
                     e = e.next) {
                    Object k;
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                }
                return null;
            }

        containsValue方法就比較粗暴了,就是直接遍歷所有元素直到找到value,由此可見HashMap的containsValue方法本質(zhì)上和普通數(shù)組和list的contains方法沒什么區(qū)別,你別指望它會(huì)像containsKey那么高效

        public boolean containsValue(Object value) {
            if (value == null)
                    return containsNullValue();
        
            Entry[] tab = table;
                for (int i = 0; i < tab.length ; i++)
                    for (Entry e = tab[i] ; e != null ; e = e.next)
                        if (value.equals(e.value))
                            return true;
            return false;
            }

         

      • hash和indexFor
        indexFor中的h & (length-1)就相當(dāng)于h%length,用于計(jì)算index也就是在table數(shù)組中的下標(biāo)
        hash方法是對(duì)hashcode進(jìn)行二次散列,以獲得更好的散列值
        為了更好理解這里我們可以把這兩個(gè)方法簡(jiǎn)化為 int index= key.hashCode()/table.length,以put中的方法為例可以這樣替換
        int hash = hash(key.hashCode());//計(jì)算hash
        int i = indexFor(hash, table.length);//計(jì)算在數(shù)組中的存儲(chǔ)位置
        //上面這兩行可以這樣簡(jiǎn)化
        int i = key.key.hashCode()%table.length;

         

      •   static int hash(int h) {
                // This function ensures that hashCodes that differ only by
                // constant multiples at each bit position have a bounded
                // number of collisions (approximately 8 at default load factor).
                h ^= (h >>> 20) ^ (h >>> 12);
                return h ^ (h >>> 7) ^ (h >>> 4);
            }
        
        
            static int indexFor(int h, int length) {
                return h & (length-1);
            }

         

      HashMap的簡(jiǎn)化實(shí)現(xiàn)MyHashMap

      為了加深理解,我個(gè)人實(shí)現(xiàn)了一個(gè)簡(jiǎn)化版本的HashMap,注意哦,僅僅是簡(jiǎn)化版的功能并不完善,僅供參考

      package cn.lzrabbit.structure;
      
      /**
       * Created by rabbit on 14-5-4.
       */
      public class MyHashMap {
      
          //默認(rèn)初始化大小 16
          private static final int DEFAULT_INITIAL_CAPACITY = 16;
          //默認(rèn)負(fù)載因子 0.75
          private static final float DEFAULT_LOAD_FACTOR = 0.75f;
      
          //臨界值
          private int threshold;
      
          //元素個(gè)數(shù)
          private int size;
      
          //擴(kuò)容次數(shù)
          private int resize;
      
          private HashEntry[] table;
      
          public MyHashMap() {
              table = new HashEntry[DEFAULT_INITIAL_CAPACITY];
              threshold = (int) (DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
              size = 0;
          }
      
          private int index(Object key) {
              //根據(jù)key的hashcode和table長(zhǎng)度取模計(jì)算key在table中的位置
              return key.hashCode() % table.length;
          }
      
          public void put(Object key, Object value) {
              //key為null時(shí)需要特殊處理,為簡(jiǎn)化實(shí)現(xiàn)忽略null值
              if (key == null) return;
              int index = index(key);
      
              //遍歷index位置的entry,若找到重復(fù)key則更新對(duì)應(yīng)entry的值,然后返回
              HashEntry entry = table[index];
              while (entry != null) {
                  if (entry.getKey().hashCode() == key.hashCode() && (entry.getKey() == key || entry.getKey().equals(key))) {
                      entry.setValue(value);
                      return;
                  }
                  entry = entry.getNext();
              }
              //若index位置沒有entry或者未找到重復(fù)的key,則將新key添加到table的index位置
              add(index, key, value);
          }
      
          private void add(int index, Object key, Object value) {
              //將新的entry放到table的index位置第一個(gè),若原來有值則以鏈表形式存放
              HashEntry entry = new HashEntry(key, value, table[index]);
              table[index] = entry;
              //判斷size是否達(dá)到臨界值,若已達(dá)到則進(jìn)行擴(kuò)容,將table的capacicy翻倍
              if (size++ >= threshold) {
                  resize(table.length * 2);
              }
          }
      
          private void resize(int capacity) {
              if (capacity <= table.length) return;
      
              HashEntry[] newTable = new HashEntry[capacity];
              //遍歷原table,將每個(gè)entry都重新計(jì)算hash放入newTable中
              for (int i = 0; i < table.length; i++) {
                  HashEntry old = table[i];
                  while (old != null) {
                      HashEntry next = old.getNext();
                      int index = index(old.getKey());
                      old.setNext(newTable[index]);
                      newTable[index] = old;
                      old = next;
                  }
              }
              //用newTable替table
              table = newTable;
              //修改臨界值
              threshold = (int) (table.length * DEFAULT_LOAD_FACTOR);
              resize++;
          }
      
          public Object get(Object key) {
              //這里簡(jiǎn)化處理,忽略null值
              if (key == null) return null;
              HashEntry entry = getEntry(key);
              return entry == null ? null : entry.getValue();
          }
      
          public HashEntry getEntry(Object key) {
              HashEntry entry = table[index(key)];
              while (entry != null) {
                  if (entry.getKey().hashCode() == key.hashCode() && (entry.getKey() == key || entry.getKey().equals(key))) {
                      return entry;
                  }
                  entry = entry.getNext();
              }
              return null;
          }
      
          public void remove(Object key) {
              if (key == null) return;
              int index = index(key);
              HashEntry pre = null;
              HashEntry entry = table[index];
              while (entry != null) {
                  if (entry.getKey().hashCode() == key.hashCode() && (entry.getKey() == key || entry.getKey().equals(key))) {
                      if (pre == null) table[index] = entry.getNext();
                      else pre.setNext(entry.getNext());
                      //如果成功找到并刪除,修改size
                      size--;
                      return;
                  }
                  pre = entry;
                  entry = entry.getNext();
              }
          }
      
          public boolean containsKey(Object key) {
              if (key == null) return false;
              return getEntry(key) != null;
          }
      
          public int size() {
              return this.size;
          }
      
          public void clear() {
              for (int i = 0; i < table.length; i++) {
                  table[i] = null;
              }
              this.size = 0;
          }
      
      
          @Override
          public String toString() {
              StringBuilder sb = new StringBuilder();
              sb.append(String.format("size:%s capacity:%s resize:%s\n\n", size, table.length, resize));
              for (HashEntry entry : table) {
                  while (entry != null) {
                      sb.append(entry.getKey() + ":" + entry.getValue() + "\n");
                      entry = entry.getNext();
                  }
              }
              return sb.toString();
          }
      }
      
      class HashEntry {
          private final Object key;
          private Object value;
          private HashEntry next;
      
          public HashEntry(Object key, Object value, HashEntry next) {
              this.key = key;
              this.value = value;
              this.next = next;
          }
      
          public Object getKey() {
              return key;
          }
      
          public Object getValue() {
              return value;
          }
      
          public void setValue(Object value) {
              this.value = value;
          }
      
          public HashEntry getNext() {
              return next;
          }
      
          public void setNext(HashEntry next) {
              this.next = next;
          }
      }
      MyHashMap

       

      posted @ 2014-05-11 10:19  懶惰的肥兔  閱讀(27799)  評(píng)論(3)    收藏  舉報(bào)
      主站蜘蛛池模板: 亚洲中文字幕日产无码成人片| 欧美牲交a欧美牲交aⅴ免费真| 嫖妓丰满肥熟妇在线精品| 樱桃视频影院在线播放| 欧美老熟妇喷水| 日韩精品一区二区蜜臀av| 不卡一区二区国产精品| 久久香蕉国产亚洲av麻豆| 亚洲成人动漫av在线| 国产国拍亚洲精品永久软件| 亚洲国产日韩a在线播放| 日本无码欧美一区精品久久| 九九热视频在线精品18| 国产精品高清中文字幕| 成人国产片视频在线观看| 精品少妇人妻av无码专区| 亚洲av麻豆aⅴ无码电影| 黑人av无码一区| 无码人妻一区二区三区av| 91精品久久一区二区三区| 日韩av中文字幕有码| 国产午夜亚洲精品国产成人 | 中文字幕人妻av第一区| 国产成人一区二区三区免费| 久久乐国产精品亚洲综合| 日本边添边摸边做边爱喷水 | 亚洲精品自拍视频在线看| 亚洲欧美日韩愉拍自拍美利坚| 99精品久久久久久久婷婷| 国产在线一区二区不卡| 久久热这里只有精品99| 免费无码又爽又刺激高潮虎虎视频 | 亚洲欧洲无码av电影在线观看| 国产丰满乱子伦午夜福利| 久久香蕉国产线看观看怡红院妓院| 在线观看无码av五月花| 久热这里只有精品视频3| 熟妇人妻无码中文字幕老熟妇| 最新中文字幕av无码专区不| 成人福利国产午夜AV免费不卡在线| 99久久精品费精品国产一区二 |