HashMap, HashTable, HashSet分析

HashMap分析:

  • 其主要特性:(key-value)存儲,key-value可爲NULL, 非線程安全。
  • 其主要屬性:
//默認容量微16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//最大容量2^30
static final int MAXIMUM_CAPACITY = 1 << 30;
//默認裝載因子0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//空表
static final Entry<?,?>[] EMPTY_TABLE = {};
//默認空表
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
//元素個數
transient int size;
//擴容閾值
int threshold;
//裝載因子:table中裝入的元素/table的長度,超過此值會resize table
final float loadFactor;

看看其構造函數: java

public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);

        this.loadFactor = loadFactor;
        threshold = initialCapacity;
        init(); //空實現,子類可Override
    }

HashMap中的元素就是經過Entry的數組實現,Entry爲: 算法

static class Entry<K,V> implements Map.Entry<K,V> {
     final K key;
     V value;
     Entry<K,V> next; //後節點引用,HashMap採用連接表解決Hash衝突
     int hash; //對應key的hash值
}
看看比較重要的put, get, remove等方法:

put方法實現: 數組

圖解即爲: 安全

實現代碼: ide

public V put(K key, V value) {
    if (table == EMPTY_TABLE) {
        inflateTable(threshold);//若爲空表,就擴容
    }
    if (key == null)
        return putForNullKey(value); //若key爲null, hash值爲0
    int hash = hash(key); //根據key對象,算出其hash值
    int i = indexFor(hash, table.length); //由hash值映射到table中某位置
    for (Entry<K,V> e = table[i]; e != null; e = e.next) { //是否有相同的key對象,有則替換原來的值,且返回舊值
         Object k;
         if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {//注意key類得Override equals,hashCode方法
             V oldValue = e.value;
             e.value = value;
             e.recordAccess(this);
             return oldValue;
         }
    }
    modCount++;
    addEntry(hash, key, value, i);
    return null;
}
看看inflateTable()方法:
private void inflateTable(int toSize) {
   // 找到一個大於toSize,且爲2的指數被的容量大小,方便hash值計算和元素索引計算
   int capacity = roundUpToPowerOf2(toSize);
   threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
   table = new Entry[capacity];
   initHashSeedAsNeeded(capacity);
}

看看hash值怎麼計算的: 函數

final int hash(Object k) {
    int h = hashSeed;
    if (0 != h && k instanceof String) {
        return sun.misc.Hashing.stringHash32((String) k);
    }
    h ^= k.hashCode();
    h ^= (h >>> 20) ^ (h >>> 12);
    return h ^ (h >>> 7) ^ (h >>> 4);
}
獲得了key對象hash值,還要算出其在table數組中的索引,看indexFor():
static int indexFor(int h, int length) {
   //這裏很巧,能保證不管hash值爲多少,算出的索引都在數組索引範圍內    
   return h & (length-1);
}

再看看怎麼講一個元素添加到table中的,addEntry()方法: this

void addEntry(int hash, K key, V value, int bucketIndex) {
    if ((size >= threshold) && (null != table[bucketIndex])) {//超過閾值,且table[butcketIndex]不爲空
        resize(2 * table.length); //擴容爲原來2倍,HashMap沒有提供定製擴容大小,怕你亂來
        hash = (null != key) ? hash(key) : 0; //從新計算hash值
        bucketIndex = indexFor(hash, table.length); //table變了,從新計算index
    }
    createEntry(hash, key, value, bucketIndex); //建立Entry
}

void createEntry(int hash, K key, V value, int bucketIndex) {
    Entry<K,V> e = table[bucketIndex];
    table[bucketIndex] = new Entry<>(hash, key, value, e); //插入Entry, 至關於再鏈表頭插入
    size++;
}

對於get方法: spa

public V get(Object key) {
    if (key == null)
       return getForNullKey();
    Entry<K,V> entry = getEntry(key);
    return null == entry ? null : entry.getValue();
}

final Entry<K,V> getEntry(Object key) {
    if (size == 0) {
        return null;
    }

    int hash = (key == null) ? 0 : hash(key); //計算hash
    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;
}
對於remove方法:
public V remove(Object key) {
     Entry<K,V> e = removeEntryForKey(key);
     return (e == null ? null : e.value);
}

final Entry<K,V> removeEntryForKey(Object key) {
    if (size == 0) {
        return null;
    }
    int hash = (key == null) ? 0 : hash(key); //計算hash
    int i = indexFor(hash, table.length); //計算index
    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;
}

這基本的HashMap分析。 .net

HashTable分析:

對於HashTable,與HashMap原理基本一致,這裏就說其與HashMap的不一樣之處: 線程

  • HashTable對方法進行了synchronized, 所以線程安全,也是最大的區別;
  • 默認容量不一樣:
public Hashtable() {
    this(11, 0.75f); //默認容量爲11
}
  • key,value都不能爲空, 擴容大小機制不一樣,Entry索引計算不一樣:
public synchronized V put(K key, V value) {
   // value不能爲null
   if (value == null) {
       throw new NullPointerException();
   }
   Entry tab[] = table;
   int hash = hash(key); //計算hash
   int index = (hash & 0x7FFFFFFF) % tab.length; //計算index
   for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
         if ((e.hash == hash) && e.key.equals(key)) {
             V old = e.value;
             e.value = value;
             return old;
         }
   }

   modCount++;
   if (count >= threshold) {
       // Rehash the table if the threshold is exceeded
       rehash(); //擴容
       tab = table;
       hash = hash(key);
       index = (hash & 0x7FFFFFFF) % tab.length;
   }

   // Creates the new entry.
   Entry<K,V> e = tab[index];
   tab[index] = new Entry<>(hash, key, value, e);
   count++;
   return null;
}

其擴容函數rehash():

protected void rehash() {
     int oldCapacity = table.length;
     Entry<K,V>[] oldMap = table;

     //擴容爲2倍+1
     int newCapacity = (oldCapacity << 1) + 1;
     if (newCapacity - MAX_ARRAY_SIZE > 0) {
          if (oldCapacity == MAX_ARRAY_SIZE)
             return;
         newCapacity = MAX_ARRAY_SIZE;
     }
     Entry<K,V>[] newMap = new Entry[newCapacity];
     modCount++;
     threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
     boolean rehash = initHashSeedAsNeeded(newCapacity);
     table = newMap;
     for (int i = oldCapacity ; i-- > 0 ;) { //從新hash鏈表中的Entry到新table
         for (Entry<K,V> old = oldMap[i] ; old != null ; ) {
             Entry<K,V> e = old;
             old = old.next;
             if (rehash) {
                 e.hash = hash(e.key);
             }
             int index = (e.hash & 0x7FFFFFFF) % newCapacity;
             e.next = newMap[index];
             newMap[index] = e;
         }
     }
}
  • hash算法不一樣:
private int hash(Object k) {
     return hashSeed ^ k.hashCode();
}

之後,就不用怕人問你HashMap和HashTable的區別,你就只知道同步問題,直接把代碼寫給他看,對於同步HashMap, 另外會分析ConcurrentHashMap的實現:http://my.oschina.net/indestiny/blog/209458

HashSet分析:

對於HashSet, 其實現徹底分發給內部的HashMap成員變量,僅利用HashMap的key來實現, 從其屬性便知:

private transient HashMap<E,Object> map;
//map的值都爲這個對象
private static final Object PRESENT = new Object();

其add,remove方法都分發給了map對象:

public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}

public boolean remove(Object o) {
    return map.remove(o)==PRESENT;
}
以上就簡單分析了HashMap,HashTable,HashSet。

不吝指正。

相關文章
相關標籤/搜索