java数据结构:HashMap

 一,Map<String,String> map = new HashMap<String,String>();

 由数组和链表组成:
 class Node{
     final int hash = 0;
     Object key;
     Object value;
     Node next;
 }

 Node[] element;

二,HashMap源码介绍:

     //初始数组大小
     static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 
     //最大数据大小
     static final int MAXIMUM_CAPACITY = 1 << 30;
     // 负载因子:数组到达一定长度就开始扩容
     static final float DEFAULT_LOAD_FACTOR = 0.75f; 
     //链表的临界值 当链表长度超过8 的时候,就将链表改变为平衡二叉树(红黑树)
     static final int TREEIFY_THRESHOLD = 8;


  Map map =new HashMap<String,String>();
  public HashMap() {
   //初始负载因子,并没有初始化  hashmap 的大小
   this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
  }
  
  //put 操作
  map.put("key","value");
  final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
         //如果node是空,开始初始化
         n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
         //(n-1)&hash ????  n是hashmap数组的长度,前面规定长度是2的倍数那么(n-1)就一直011111这样,高位补0,
         //hash值和(n-1) 取 & ;结果还是在0-(n-1)之间;
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                // hash值一样,key值也是一样,表示在hashmap中已经有了 这个值,直接替换掉
            e = p;
            else if (p instanceof TreeNode)
            //表示已经是 treeNode了,就用treenode的方式去解决问题
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
            //是链表的存储方式
                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);
                        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;
    }


 三, 数组长度是2的n次方??? 因为(n-1)= 0111111,如果不是2的n次方,n-1就会出现 011101这种,中间含有0操作,
   那么任何hash值取&这个点都是0,那么这个地方就永远放不到值,数组的容量就变小了,浪费空间

   static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

   所以在resize的时候,是进行双倍扩容的。

   为啥还要将key的高位右移16在取&???
   是因为key的值值会和数组长度进行取&,数组的长度在绝大部分情况下 并不会超过,2<<16
   那么key的高16位基本上就是浪费了,在hashmap中hash的分布就没有想象的中的分散,导致碰撞加剧

   final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
      //超过上限了  那就GG吧 别操作了
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        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 就用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;
                     //hash 值和数组oldCap的长度进去取&,计算hash值在oldcap的最高位长度哪里是0 还是1,是0 取&就=0
                     //是1,取&就是1,那么就会出现两种情况,=0的时候,重新分配还是原来的地方,=1的时候长度增加了
                     oldcap的位置;
                            if ((e.hash & oldCap) == 0) {
                        //重新设置一个链表,放置位置没变的node
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                     //重新设置一个量表,将位置扩大oldcap那么大的node放在一个链表中
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                     //老位置放置  = 0 的node
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                     //j+oldcap 处放置 = 1 的node
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }


 四,为啥hashmap不是线程安全的?
      在多线程条件下,map就是一个共享变量,同时操作如果是put,就会导致此处的put混乱,在resize()
      的时候,最后一个线程的table[]赋值进去,其它线程的数据可能就丢失了,甚至会导致线程死循环?
   为啥死循环。。?

      线程1和线程2同时进行resize()操作:
      原始数组:
      a -> b -> c

      线程1,开始扩容,依次进行遍历最后形成了
      c -> b -> a

      但是此时还没放进到共享变量里面,只是还在栈帧里面;
      而此时线程2开始了resize()操作;
      第一个值为 a 取第二个值时候还是b,b ->a
      问题出现了:
      线程1此刻把数据刷到内存来了此刻的数据就是c -> b -> a;那么 线程2找a.next() 刚好变成了a了,
      最终变成了    a.next = b;b.next =a
      map.get("c") 就变成死循环了;

猜你喜欢

转载自blog.csdn.net/waterflying2015/article/details/81270527