HashMap和HashTable與ConcurrentHashMap區別和使用場景

HashMap與HashTable來自那?

Map

HashMap是什麼? 結構圖什麼樣?

在這裏插入圖片描述
擴容操作
在這裏插入圖片描述

HashTable是什麼?

HashTable已經不怎麼使用,主要是比Hashmap線程安全

HashMap與HashTable的區別

HashMap與HashTable的key和Value是否可以爲空

HashMap

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

Hashtable

 public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
  

HashMap與HashTable 是否是線性安全

HashMap

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

在這裏插入圖片描述

Hashtable

 public synchronized V put(K key, V value) 

在這裏插入圖片描述

HashMap與HashTable 初始值大小,最大容量,負載因子

HashMap
默認長度16

    /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

最大值

     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

負載因子

    /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

節點數大於8轉換爲紅黑樹

static final int TREEIFY_THRESHOLD = 8;

Hashtable

默認是11,負載因子默認0.75

    /**
     * Constructs a new, empty hashtable with a default initial capacity (11)
     * and load factor (0.75).
     */
    public Hashtable() {
        this(11, 0.75f);
    }

HashMap解決衝突問題

// 如果hash和key,equal都相等,則把新值賦給舊值
 if (p.hash == hash &&  ((k = p.key) == key || (key != null && key.equals(k))))
 e = p;

什麼時候衝突
threshold 表示閾值
table.length長度
loadFactor 表示負載因子

當threshold 閥值 = table.length * loadFactor , 當鍵值對對個數size大於threshold則表示需要擴容

如何把HashMap變成線程安全的

   Collections.synchronizedCollection(Arrays.asList("a"));
   //互斥對象成員
    final Object mutex;     // Object on which to synchronize

ConcurrentHashMap

基於分段鎖進行處理, 他的好處就是hashTable使用利用的sync,屬於方法鎖,效率不好,所以我們更改把數據進行分段,然後鎖分段的數據所以效率就高了, 處理數據的分段,他也是採用跟HashMap一樣的結構
JDK7
在這裏插入圖片描述
JDK8
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章