hashmap簡介

  • hashmap是一個鍵值對的無序數組。經過hashcode指引內存地址獲取值。
    hashmap不是有序數組,也不是散列鏈表,他能夠理解爲一個無序的數組,經過hashcode去映射。數組

    hashmap在第一次put的時候,會初始化鍵值對數組的大小16,加載因子0.75,當數組超過16*0.75=12的時候,數組會擴容2倍。this

    hashmap的put方法源碼
    public V put(K key, V value) {
    if (table == EMPTY_TABLE) {
    //若是第一次加載,判斷是空數組,初始化大小16
    inflateTable(threshold);
    }
    if (key == null)
    //hashmap支持null鍵,經過單獨的方法put
    return putForNullKey(value);
    //獲取key的hashcode,若是有就替換舊的value
    int hash = hash(key);
    //獲取hashcode在數組中的索引
    int i = indexFor(hash, table.length);
    //
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
    Object k;
    //若是當前索引有value,就替換
    if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
    V oldValue = e.value;
    //將新value放到e.v中
    e.value = value;
    //沒任何實現,是個空方法
    e.recordAccess(this);
    return oldValue;
    }
    }
    //結構性更改次數加1
    modCount++;
    //添加新元素
    addEntry(hash, key, value, i);
    return null;
    }code

    //添加元素方法
     void addEntry(int hash, K key, V value, int bucketIndex) {
    threshold就是16*0.75,當map在使用75%時候會擴容
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }
       //添加元素
        createEntry(hash, key, value, bucketIndex);
    }

    hashmap get方法;
    public V get(Object key) {
    if (key == null)
    return getForNullKey();
    Entry<K,V> entry = getEntry(key);索引

    return null == entry ? null : entry.getValue();
    }
    
    
    //獲取hashcode,直接獲取值,效率高
     final Entry<K,V> getEntry(Object key) {
        if (size == 0) {
            return null;
        }
    
        int hash = (key == null) ? 0 : hash(key);
        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;
    }
相關文章
相關標籤/搜索