美文网首页
java集合之HashMap

java集合之HashMap

作者: PuHJ | 来源:发表于2018-08-23 17:58 被阅读17次

一、hashcode 和 equals关系

先以一个小例子入手:

public class HashTest {

    public static void main(String[] args) {

        HashMap<Book,String> map = new HashMap<>();
        Book b = new Book(1,"java");
        map.put(b, "String");
        System.out.println((b.hashCode() +"    "+ new Book(1,"java").hashCode()));
        System.out.println(map.get(new Book(1,"java")));
    }
    
}

class Book {
    
    public int price;
    public String name;
    
    public Book(int price, String name) {
        super();
        this.price = price;
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Book other = (Book) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }   
}

这是个只重写了equals(),并没有重写hashcode()。上面运行的结果如下:
2018699554 1311053135
null
也就是没有重写的hashcode值,是系统处理的,内容一致的对象hashcode并不一定相同。第二点就是HashMap会根据Key的hashcode来决定放在哪个数组中,不同的hashcode当然得不到想要的Value。
对于hashcod()和equals()几点建议:

  • equals相等,它的hashcode也一定要相等
  • 重写了hashcode,也一定要重写equals
  • equals要满足对称、反射、传递特性

二、HashMap

结构

HashMap的存储方式是数组+链表的形式,数组也叫作桶,hashcode | (数组大小-1)相等的Key放在同一个链表中。先看几个属性定义:

     //默认数组的长度
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    // 数组的最大上限
    static final int MAXIMUM_CAPACITY = 1 << 30;

    // 默认加载因子,如果DEFAULT_LOAD_FACTOR * CAPACITY < 元素个数,就需要扩容调整 
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    //  链表的结构定义
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;   
     }

首先最常见的问题是:数组的长度为什么只能是2的次方大小?

    // 使用低16位避免冲突
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

如何根据Key的hashcode,将元素尽量平均的放入了桶中。如果采用非2次方会有什么影响了?
假设是数组的长度是15,那么15 - 1 = 1110;在与1110作与运算的时候,尾部永远都是0,事实上只有三位数有效,那么长度为15的数组只有8个用到了,剩下的都浪费了。那么采用除以长度取余的方式不就可以解决数组浪费的问题了嘛,但是取余的效率比按位与的方式差多了。

小结:

  • 不是2的次方,会造成数组资源浪费的问题
  • 采用取余的方法,没有按位与的效率高

HashMap的添加操作put

添加操作是HashMap的核心,会涉及到链表插入和重新扩容。
HashMap是支持null作为key或者value的

   // 添加入口
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    // 查找Key是不是之前插入过了,插入过了就直接返回,否则放在链表末尾
    // 如果数组还没初始化,则要resize()操作,如果单链表长度过大则treeifyBin(tab, hash),将其树化存储;
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // 如果桶为null或长度为0,需要重新分配大小,相当于懒加载模式,使用时才初始化
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 核心  按位与来查找元素在哪个桶上面,该桶的元素还没有,直接放在第一个即可
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
           // 找到该链表的第一个元素跟插入的元素的key是一样的,说明原本就插入过这个key
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
           // 寻找之前有没有插入过这个key ,如果e不为null就代表有
            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;
                }
            }
             // existing mapping for key
            if (e != null) {
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

现在看下扩容的方法resize(),遍历数组的,在递归链表,取出子元素按照新的规范存储

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

相关文章

网友评论

      本文标题:java集合之HashMap

      本文链接:https://www.haomeiwen.com/subject/ydrmiftx.html