HashMap1.7 1.8 HashTable 源码分析面试考点

一部分 基础篇

1.Hashmap 

1.1 hashMap 极其常见的一种数据格式。

  key-value 形式存放数据;

key 可以为null ;

默认大小为16,负载因子0.75,阈值12;

1.2 遍历map的几种方式: 

  public static void main(String[] args) {
        HashMap <String ,String> map = new HashMap<String, String>();
        map.put("a","1");
        map.put("b","2");
        map.put(null,"3");
        // 遍历 map
        //1.map.entrySet()
        for(Map.Entry<String,String> entry :map.entrySet()){
            String  key =entry.getKey();
            String value =entry.getValue();
        }
       
        // 2.map.entrySet().iterator
        Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String, String > entry =it.next();
            String key = entry.getKey();
            String  value = entry.getValue();
        }
        //3. map.keySet()
        for(String key :map.keySet()){
            String k = key;
            String value = map.get(key);
        }
    }

1.3 map 的常用方法(结合源码 jdk1.7)

1.3.1 继承AbstractMap ,实现Map类

public class HashMap<K,V>
    extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable

1.3.2 几个重要的变量

//初始化的默认容量 16 (1<<4)1向右移动4位 二进制 10000
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 
// 最大容量不超过这个
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默认的加载因子  0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 空数组,定义是 当表没有被初始化的时候的实例
 /**
     * An empty table instance to share when the table is not inflated.
     */
static final Entry<?,?>[] EMPTY_TABLE = {};
// 这个是 初始化的表,大小是可以调试的,但必须是2的幂
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
 // map 的size
transient int size;
//如果初始化的表为空,那么这个的值就是默认的容量值
//这个因素就是容量值
int threshold;

//系数  加载因子
final float loadFactor;
//  这个参数指的是 hashmap被修改的次数,和fail-fast机制
transient int modCount;

 

1.3.3 构造函数

构造函数一共有四个

1.// 初始化大小 和加载因子
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();
    }

2.初始化大小,加载因子是默认的

public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
3. 无参构造
public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }
4.  参数是个,map ,初始化大小选择  (m原本大小/默认加载因子 ) 和(默认大小)取大的
  public HashMap(Map<? extends K, ? extends V> m) {
        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
                      DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
        inflateTable(threshold);

        putAllForCreate(m);
    }

1.3.4 几个重要的方法

get()方法 

get()的思路是,先判断是不是为null,
如果为null,getForNullkey(),返回key=null的value的值;
如果不是null,getEntry(),根据key的hash值从table[]数组表中查找;
定位到数组的具体位置之后,比较key值是否相等,如果key不相等,e=e.next()指向下一个;
一直找到相等的key之后,返回entry,entry.value() 就是对应的值了。

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

        return null == entry ? null : entry.getValue();
    }

private V getForNullKey() {
        if (size == 0) {
            return null;
        }
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null)
                return e.value;
        }
        return null;
    }
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;
    }

put方法

//1 如果table==  EMPTY_TABLE,说明是第一次添加值,此时的map还没有分配容量;调用inflateTable方法,分配容量,并且初始化数组。
//2 判断key == null,如果是泽覆盖原本key =null的值;
//3 计算keyhash值, 找到对应的数组位置,
//  找到对应的key值;如果有key,则覆盖原值,并返回方法结束;
//  如果插入的key值是新的值,调用addEntry()方法,modcount++;
调用addEntry的时候,先进行是否进行扩容判断;
如果扩容,扩容大小将是原来的两倍或者最大值;
然后,将新的元素添加到bucketIndex的位置进去;




public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);
        int i = indexFor(hash, table.length);
        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;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

    private void inflateTable(int toSize) {
        // Find a power of 2 >= toSize
        int capacity = roundUpToPowerOf2(toSize);

        threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
        table = new Entry[capacity];
        initHashSeedAsNeeded(capacity);
    }
//  扩容的条件 ,a 当前个数是否大于等于阙值
                b  当前是否发生哈希碰撞

 void addEntry(int hash, K key, V value, int bucketIndex) {
        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);
    }
// 扩容方法  先判断新的容量大小是不是超过最大值;新建一个数组;将原数组的值迁移到新数组中去。
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, initHashSeedAsNeeded(newCapacity));
        table = newTable;
        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    }

putAll()方法

// 先判断是不是入参为0;
//在判断 是不是没有初始化,如果没,就大小取 加载因子* size大小和 threshold的最大值。
//在判断 如果阙值小于< 入参map的size
public void putAll(Map<? extends K, ? extends V> m) {
        int numKeysToBeAdded = m.size();
        if (numKeysToBeAdded == 0)
            return;

        if (table == EMPTY_TABLE) {
            inflateTable((int) Math.max(numKeysToBeAdded * loadFactor, threshold));
        }
       // 如果阙值小于size,则targetCapacity = numKeysToBeAdded / loadFactor + 1 和 newCapacity 进行比较;
       
     
        if (numKeysToBeAdded > threshold) {
    
            int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
            if (targetCapacity > MAXIMUM_CAPACITY)
                targetCapacity = MAXIMUM_CAPACITY;
            int newCapacity = table.length;
            while (newCapacity < targetCapacity)
                newCapacity <<= 1;
            if (newCapacity > table.length)
                resize(newCapacity);
        }

        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
            put(e.getKey(), e.getValue());
    }

 

remove()方法

// 判断 key==null,如果是,求出hash值,根据hash值定位到 具体的值,如果有hash冲突,
确定好key值之后,让当前table[i] =next。

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);
        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;
    }

 containkey()方法

判断size==null
判断hash值 定位到table[]数组位置,找到具体的key值。
public boolean containsKey(Object key) {
        return getEntry(key) != null;
    }
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;
    }

hashcode的计算方法

hashcode的获取方法 h 和table,length做且运算
static int indexFor(int h, int length) {
        // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
        return h & (length-1);
    }

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);
    }

1.4 基于jdk1.7的

HashMap 的形式就是 单向链表+数组,根据hashcode确定数组位置,然后有hash冲突就单向链表;

HashMap  加载因子0.75 阙值是0.75*初始化容量, 扩容是原先大小的2倍。扩容条件是新插入的时候,size的长度大于阙值,并且table[i],即当前位置不null,即有hash冲突。

2.HashTable

2.1 Hashtable 特点

hashtable 与hashmap十分的相似,也是存放键值对,但是key 和value都不可以为null;

2.2 HashTable 源码解析(基于jdk1.8)

观看hashtable 的源码发现,其实他和hashMap相似度高了去了。您请往下看:

这是table常用的方法,放眼一看,尼玛 这和hashMap有个鸡儿区别,不行咱们得去看看源码去:

hashTable 继承了Dicionary<K V>这个么个父类,然后实现的也是Map接口;这一点想想也是,HashMap和HashTable功能如此相似,肯定实现了同一个接口

几个重要的变量:

这都是熟悉的老面孔啊,没毛病,在hashMap中已经见过了!

private transient Entry<?,?>[] table; 数组
private int threshold;阙值
private float loadFactor;加载因子
private transient int modCount = 0; 修改次数

四个构造函数:

别闹 怎么参数都和HashMap一个鸡儿样,果然是吃同一个奶长大的两兄弟!

入参 初始化容量和加载因子,但是在这里他是直接new Entry[]数组;

  经典方法 put()

 //  第一 它加了synchronized 关键字,保证了线程的安全性。
//   value不可以为null否则空指针异常
// 确定hash值
//看是否为null,不为null就查找是否有存在的key进行替换;
//为null就直接添加

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.
//注意: 先计算出hash值,然后把hash值与0x7FFFFFFF与运算得到一个整数,然后确定了table索引的位置;
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        for(; entry != null ; entry = entry.next) {
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }

        addEntry(hash, key, value, index);
        return null;
    }
 // 添加的时候,,首先modCount++操作;
//count是否达到阙值如果没有就添加就ok了;
// 如果达到阙值,进行rehash()操作,rehash完成之后,重新计算index的位置
   private void addEntry(int hash, K key, V value, int index) {
        modCount++;

        Entry<?,?> tab[] = table;
        if (count >= threshold) {
            // Rehash the table if the threshold is exceeded
            rehash();

            tab = table;
            hash = key.hashCode();
            index = (hash & 0x7FFFFFFF) % tab.length;
        }

        // Creates the new entry.
        @SuppressWarnings("unchecked")
        Entry<K,V> e = (Entry<K,V>) tab[index];
        tab[index] = new Entry<>(hash, key, value, e);
        count++;
    }
//具体的rehash操作:newcapacity 是原先table数组长度的2倍;modcount++;

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

        // overflow-conscious code
        int newCapacity = (oldCapacity << 1) + 1;
        if (newCapacity - MAX_ARRAY_SIZE > 0) {
            if (oldCapacity == MAX_ARRAY_SIZE)
                // Keep running with MAX_ARRAY_SIZE buckets
                return;
            newCapacity = MAX_ARRAY_SIZE;
        }
        Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];

        modCount++;
        threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
        table = newMap;
        // 注意:首先它是倒着来的从数组最后一个元素开始;
        // 然后在某个元素下,把第一个entry放在了最后一个,让第二个放在了倒数第二个以此类推。
      //相当于单链表反向过来了
        for (int i = oldCapacity ; i-- > 0 ;) {
            for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
                Entry<K,V> e = old;
                old = old.next;

                int index = (e.hash & 0x7FFFFFFF) % newCapacity;
                e.next = (Entry<K,V>)newMap[index];
                newMap[index] = e;
                a b c d
                
                     old=a ;e=old=a ;old=b; a.next=new[i] new[i]=a;
                            e=old=bl old=c; e.next= new[i] new[i]=e=b;
  
                     

            }
        }
    }

 

remove方法()

加锁 计算hash值,找到对应的位置 谈话pre.next=e.next或者 table[i] =next;

public synchronized V remove(Object key) {
    Entry<?,?> tab[] = table;
    int hash = key.hashCode();
    int index = (hash & 0x7FFFFFFF) % tab.length;
    @SuppressWarnings("unchecked")
    Entry<K,V> e = (Entry<K,V>)tab[index];
    for(Entry<K,V> prev = null ; e != null ; prev = e, e = e.next) {
        if ((e.hash == hash) && e.key.equals(key)) {
            modCount++;
            if (prev != null) {
                prev.next = e.next;
            } else {
                tab[index] = e.next;
            }
            count--;
            V oldValue = e.value;
            e.value = null;
            return oldValue;
        }
    }
    return null;
}

二、 比较HashMap 1.7版本和1.8版本的区别:

1.8的hashMap 不再是table数组了 而是换成了 

Node静态类 ,有几个组成部分包括 hash ,key,value ,next(指向下一个数组)

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

put方法:

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
     // table==null 扩容操作
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 如果没有hash冲突 直接新生成,赋值就可以了
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
       //存在hash冲突的情况  判断如果当前的key和hash符合 就直接存入让e=p;
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
//  如果判断是不是一个 treeNode,红黑树就直接存放到红黑树中去 
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
 //如果不是判断链表的长度是否大于8
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {//插入尾部
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);//如果大于8就直接转换成红黑树。
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

 get的方法:

// get方法
public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
// 判断在不为null的条件下,进行判断第一个的值是否符合;
如果不符合,判断下一个是不是红黑树,如果是红黑树则从红黑中查找;
如果不是红黑树,则进行遍历查找。


final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

 

好菜不怕晚 来说一下核心的扩容问题:

 final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table; //现存的table数组
        int oldCap = (oldTab == null) ? 0 : oldTab.length; // 数组长度
        int oldThr = threshold; //阙值
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {// 如果已经达到最大值
                threshold = Integer.MAX_VALUE;
                return oldTab;//返回现在的数组
            }
/如果扩大到现在的2倍之后,还能小于最大值,并且原数组长度大于等于默认初始化的容量值
//就进行扩容
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)/
                newThr = oldThr << 1; // double threshold
        }
   //运行到这一步说明 小于0数组长度,那么就是还没初始化,则进行初始化
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
// 如果阙值也小于=0,那么 就给他们默认的值初始化就可以了
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

 

扩容的核心功能:  

首先我们要明白 为什么要进行扩容?

 因为table数组的长度是一定的,随着不断的往里面put数值的时候,hash冲突肯定会越来越多,因此会影响hashmap的操作效率。那这个时候我们进行扩容就是为了更好的平衡hash冲突。

扩容的流程是什么?

  检测条件,如果当前数组的长度已经大于等于 阙值(阙值 = 加载因子*初始化容量 ),并且新插入的数组位置产生了hash冲突。

 

jdk1.8的扩容做到的操作,如果没有hash冲突 直接赋值,如果发生了冲突 如果是链表则进行链表处理。

链表的处理策略是:

用两条链表,e.hash & oldCap,做运算判断,这个的巧妙之处 因为oldcap 的值是2的次幂,所以cap的二进制值是10000,100000类似的,所以 e.hash & oldCap的结果只有两种,==0 或者==cap;=0的放到一条链表中,==cap的放入到另一条链表中,而他们的数组位置就是 table[i]即是原来的位置,和table[i+oldcap]的位置,是得更加均匀的分配到每个桶中。

 

if (oldTab != null) {

     // 遍历数组
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {//如果oldTab[j]) !=null,说明有数值


                    oldTab[j] = null; //将其置空  等待被垃圾回收
                    if (e.next == null) // e.next == null 说明 没有hash冲突 ,直接赋值就可以了
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode) // 如果是红黑树 进行红黑树处理
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order  // 如果不是红黑胡,就进行链表处理

                       / /  这里使用了两条链表进行处理
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;

                           

                          // 关于 e.hash & oldCap 的意思分析: oldcap ,与 e.hash进行与运算,最终会有两种结果,=0或者=oldcap

                       // 如果  e.hash & oldCap ==0 那么就插入到loHead 链表中

                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);

    // 将=0的都放入到 table[j]中区,

 // 对于不等于0 的就放入到table[j+oldcap中]
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }

 

为什么我们只需要e.hash&cap的运算就可以了呢?

因为jdk1,8利用了一个规律,扩容前后的hash的区别就是多了一个高位,高位是0 或者是1;cap 是2的次幂,因此他的高位肯定是1,进行e.hash&cap运算的时候,他们的结果就是=0或者=cap;

因此把元素的位置要么放在在原来table[i],要么在table[i+oldcap]位置;

最后注意一点,在原来table[i]位置的元素是正序的,而jdk1.7中是倒叙的。 。

 

看下jdk1.7的这部分代码:

确定桶的位置用的策略是:

 h & (length-1); 为什么用length-1呢?

 length=1111,111111, length-1 =1110,11110之类的,

例如 当8 (1000)和都与length16(10000)做运算结果00000;当9 (1001)和都与length16(10000)做运算结果00000;89的桶的位置就是相同的;

当8 (1000)和都与length-1 16(1111)做运算结果1000;当9 (1001)和都与length-1 15(1111)做运算结果1001;89的桶的位置就是不同的。这样就更好的减少hash冲突。同时不会发生数组越界的问题,因为最大值就是length-1;

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, initHashSeedAsNeeded(newCapacity));
    table = newTable;
    threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}

 另外,扩容得到的链表是反的; 先存在1-2-3 的到的新数组中的结果就是3-2-1;

e=1; e.next = newTable[i]=null; newTable[i] = e =1;1.next=null; 

然后

e=2,e.next = newTable[i]=1; newTable[i] = e =2;2.next=1,1.next=null;

然后 

e=3; e.next=newTable[i]=2; newTable[i] = e =3;3.next=2;2.next=11.next=null;  最终结果就是 3-2-1;

 

然鹅,这就为hashmap产生了一个致命的问题; 并发产生链表循环的问题;

例如: ab两个线程同时进行扩容,

a线程执行到 e=1,e.next=table[i]的时候挂起,

线程b开始执行,线程b执行 

e=1; e.next = newTable[i]=null; newTable[i] = e =1;1.next=null; 

e=2,e.next = newTable[i]=1; newTable[i] = e =2;2.next=1,1.next=null;  此时的table[i] =2-1;b线程挂起;

线程a继续执行:

此时e.next=table[i]就成了 e.next=table[i]=2-1;  产生循环 1-2-1;

a一直执行下去 就是  3-2-1-2-1这样的死循环;

放get(i)方法的时候,如果找不到对应的值 就会一直sixu

void transfer(Entry[] newTable, boolean rehash) {
    int newCapacity = newTable.length;
    for (Entry<K,V> e : table) {
        while(null != e) {
            Entry<K,V> next = e.next;
            if (rehash) {
                e.hash = null == e.key ? 0 : hash(e.key);
            }
            int i = indexFor(e.hash, newCapacity);
            e.next = newTable[i];
            newTable[i] = e;
            e = next;
        }
    }
}
final int hash(Object k) {
        int h = hashSeed;
        if (0 != h && k instanceof String) {
            return sun.misc.Hashing.stringHash32((String) k);
        }

        h ^= k.hashCode();

        // 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) {
    // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
    return h & (length-1);
}

1.8相比于1.7优点:

第一 1.8解决了链表死循环的问题。

第二  1.8采取的数组+链表+红黑树,更好的提高了查询性能。

当链表长于8的时候转化成红黑树,小于转换成链表。

注意的是:① hashmap被初始化的时候,数组并没有被初始化,而是在第一次put的时候进行赋值。

②无论我们初始化穿进去的初始化大小是多少 最终都会是2的次幂.找到比当前数大的第一个2次幂。

③put的时候,1.8插入链表put尾部; 1.7插入链表put头部; 

HashMap 是线程安全的么?

不是的,

第一点,resize扩容会造成死循环(在1.8中已经解决了死循环的问题);

第二点 ,put操作的时候,假如ab 两个线程 同时想插如

线程a开始执行,(key1,value1),在定位到具体的hash的位置的时候,假如此时的的插入位置的链表是2-3,还未插入,还未执行3.next = key1,a线程挂起;

b线程开始执行插入操作,(key2,value2),b的具体操作就是把(key2,value2的这个值插入进去;结果的链表 2-3-key2,对应的value2;b线程执行完成。

然后a继续执行,a现在仍然认为1是该链表的最后一个,所以插入的结果就是2-3-key2;

这样 b插入的值就被覆盖了。

如何保证线程的安全?

答曰:  Hashtable ConcurrentHashMap。

关于  ConcurrentHashMap,我们下期再聊!

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值