Java源码分析-HashMap

HashMap是非常常的集合类,我们来看下它的源码(基于JDK1.8)。

支持原创,转载请注明出处。

继承关系

public class HashMap extends AbstractMap
    implements Map, Cloneable, Serializable

HashMap实现了Map接口

核心成员变量

static final float DEFAULT_LOAD_FACTOR = 0.75f;  //默认装载因子
final float loadFactor;    //装载因子
transient Node[] table;   //数组,作为Hash桶

节点内部类

    static class Node implements Map.Entry {
        final int hash;   //hash值
        final K key;      //键
        V value;          //值
        Node next;   //指向hash值相同的下一个节点

        Node(int hash, K key, V value, Node 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;
        }
    }

这个类封装了键值对。

构造方法

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; //使用默认装载因子
    }

    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;
        this.threshold = tableSizeFor(initialCapacity);
    }

添加元素:put方法

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);  //在计算一个hash值
    }

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

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node[] tab; Node p; int n, i;
        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 {                             //存在Hash冲突
            Node e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;          
            else if (p instanceof TreeNode)   //对应桶的第一个元素是TreeNode节点,说明链表过长,已转换为红黑树
                e = ((TreeNode)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;        //找到链表中一个元素和当前节点hash值相同则跳出循环
                    p = e;   //搜索下一个节点
                }
            }
            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;
    }

put方法关键地方已经注释。首先根据key计算hash值,寻找桶,如果桶为空,则直接加入该桶,否则,将该元素加入红黑树或链表,这里就看下是如何加入链表的。首先遍历链表,如果链表中某个节点和当前元素的hash值相同,则更新节点的value值为当前元素的value值,返回节点中原来的value值。如果搜索到链表尾部,直接将要加入的节点加入链表尾部。

查询元素:get方法

    public V get(Object key) {
        Node e;
        return (e = getNode(hash(key), key)) == null ? null : e.value; //计算hash值
    }

    final Node getNode(int hash, Object key) {
        Node[] tab; Node first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {//确定桶的下标,first指向桶的第一个元素
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;     //如果第一个元素和key的hash值相同,直接返回
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode)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;      //返回空
    }

首先计算key的hash值,然后遍历红黑树或链表返回hash值相同的节点,都没找到则返回空。

支持原创,转载请注明出处。
github:https://github.com/gatsbydhn

你可能感兴趣的:(Java源码分析-HashMap)