java HashMap 学习

大体上我是根据https://www.cnblogs.com/xiaoxi/p/7233201.html学习的,原博客用到了好多图进行讲解,比较清晰,我这个博客只是用于总结一下

HashMap 是基于hash表实现的Map接口,不像hashtable,它可以null键与null值,也可以这样说,HashMap只会有一个null键,但可以有多个Null值,HashMap并不是线成安全的,如果在高并发的环境中使用,可能会造成size错误或CPU循环占用等问题.

那么第一点,什么是hash表?

 简单的来说,就是通过键值对来进行存储,只不过这个Key并不是传过来的Key,而是通过Hash函数生成的Key,可能会造成一些问题,就是key1 != key2 但是 key(key1) = key(key2) 

Hash产生大体可以分为3种算法,加法,乘法和位移

加法哈希是通过遍历数据中的元素然后每次对某个初始值进行加操作,其中加的值和这个数据的一个元素相关。

乘法哈希是通过遍历数据中的元素然后每次对初始值进行乘法操作,其中乘的值无需和数据有关系。

在JAVA中,哈希函数使用的就是乘法哈希:

//String 
private int hash; // Default to 0

public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

移位哈希是通过遍历数据中的元素然后每次对初始值进行移位操作

接下来就是HashMap的学习

那么从put开始吧

扫描二维码关注公众号,回复: 4810759 查看本文章
Map<String, Object> map = new HashMap<>();
    	map.put("one", 1);

put的时候,会对基本类型进行自动装箱

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

这两部分代码可以看出来,hashMap对key进行了 两次hash,尽量保证hashKey都不一样

在JDK1.8之前,HashMap采用数组+链表实现,即使用链表处理冲突,同一hash值的节点都存储在一个链表里。但是当位于一个桶中的元素较多,即hash值相等的元素较多时,通过key值依次查找的效率较低。而JDK1.8中,HashMap采用数组+链表+红黑树实现,当链表长度超过阈值(8)时,将链表转换为红黑树,这样大大减少了查找时间。

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)//判断键值对数组是否为空或null,若是的话,执行resize进行扩容
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null) //通过(n-1)&hash获取该对象的键在hashmap中的位置,若节点的值为Null,说明没有值,直接添加
            tab[i] = newNode(hash, key, value, null);
        else {//若有值的话,说明发生了hash冲突
            Node<K,V> e; K k;
            if (p.hash == hash && 
                ((k = p.key) == key || (key != null && key.equals(k)))) //判断table[i]的首个元素的key是否一样,若相同就直接覆盖value
                e = p;
            else if (p instanceof TreeNode) //若不是则判断table[i]是否为红黑树,若是的话,直接在树中插入键值对
                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  //若列表长度大于8,红黑树 树化
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) 若发现Key相同,直接覆盖
                        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;
    }

(n-1)&hash就等价于hash%n

Object i = map.get("one");
 public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
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) { // table已经初始化,长度大于0,根据hash寻找table中的项也不为空
            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;
    }

在jdk1.8中,resize方法是在hashmap中的键值对大于阀值时或者初始化时,就调用resize方法进行扩容;

每次扩展的时候,都是扩展2倍;

扩展后Node对象的位置要么在原位置,要么移动到原偏移量两倍的位置。

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

1.8中hashmap的确不会因为多线程put导致死循环,但是依然有其他的弊端,比如数据丢失等等。因此多线程情况下还是建议使用concurrenthashmap。

猜你喜欢

转载自blog.csdn.net/qq_35815781/article/details/85043525