java源码分析---HashMap

HashMap源码分析

1、HashMap体系结构

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

HashMap继承了AbstractMap,并实现了Map,Cloneable,Serializable接口,HashMap和Hashtable一样,底层都是基于“数组和链表”来实现的,这里两者存在的区别:HashMap继承了AbstractMap,而Hashtable继承的是Dictionary抽象类
2、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;
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;

3、构造方法
HashMap有四个构造方法,我们重点看下其中的两个
3.1 HashMap(int initialCapacity, float loadFactor)

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

产生HashMap对象,其它的构造函数都是调用此构造函数来实现的
对应的参数的说明:
initialCapacity:分配数组的大小,默认大小为16,且只能是2的幂次方
loadFactor:加载因子,作用为:当数组中存储的数据大于了分配空间的总长度*loadFactor之后就进行扩容
我们看到源码中使用了tableSizeFor(int cap)方法,其源码如下:

static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

通过源码我们了解到此函数是将我们输入的任意值转化为大于等于此值的2的幂次方。
3.2 构造方法HashMap(Map

    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

此构造函数直接使用了putMapEntries(Map

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

首先判断当前HashMap是否为空,为空的情况下根据传入的map的size来计算应构造的新的HashMap的初始容量,最后调用V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict)方法将元素存入HashMap中,此方法的源码如下:

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

此方法的思想为:首先根据key得到hashcode,根据hashcode得到要存储的位置i=hash&(n-1),其中n为数组的长度(只有n为2的幂次方时,这句话才与hash%n等价,这就解释了为什么了HashMap的容量必须为2的幂次方)。

得到存储位置i之后,检查此位置是否已经有元素,如果没有,则直接存储在该位置即可,如果有,则在位置的所有节点中遍历是否含有该key,如果已经有了该key,则更新其value即可,如果没有该key,则在该链表的末尾加入该新节点即可
上面调用了resize方法来进行扩容,前面提到,在HashMap所有的构造函数中,都没有对数组table分配存储空间。而是将这一步放入到了在put方法中进行table检测,如果为空,则调用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;
    }

此方法实现的思想为:
处理了一下两种情况
1)原table为null的情况,如果为空,则开辟默认大小的空间
2)原table不为空的情况,则开辟原来空间的2倍。由于可能oldCap*2会大于最大容量,因此也对其这种溢出情况进行了处理。
分配空间之后,然后将原数组中的元素拷贝到新数组中即可。
4、常用方法
4.1 put(K key, V value)

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

此方法直接使用了V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict)来实现的
4.2 get(Object key)

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

该方法的实现思想为:首先根据key得到hashcode,然后根据hashcode得到该key在数组table的存储位置,接着在该位置寻找key值和hashcode值一致的节点即可,如果没有找到,返回null,此方法中使用了getNode(int hash, Object key)方法,源码:

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

4.3 V remove(Object key)方法
源码如下:

    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

remove方法直接调用的是removeNode方法,而removeNode方法的思想为:先根据key的hash值找到table的位置i,然后在该位置下的链表寻找key和hash均满足条件的节点。删除节点和链表删除节点方法一致。removeNode方法源码如下:

final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) {
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                    tab[index] = node.next;
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

5、简单的说下Hashtable与HashMap的区别
以下这些摘自http://blog.csdn.net/u010412719/article/details/51980632
1、继承类不一样
HashMap继承的是AbstractMap,Hashtable继承的是Dictionary。实现的接口一致(Map、Cloneable和Serializable)
2、初始容量不一样
HashMap默认容量为16,且容量只能是2的幂次方;Hashtable默认容量为11,容量并没有2的幂次方的限制,增加的方式是 oldCap*2+1。
3、HashMap是线程不安全的,Hashtable是线程安全的
默认情况下,HashMap类中的方法并没有进行同步,而Hashtable中的方法均使用synchronized进行了同步。因此,在多线程并发时,Hashtable可以直接使用,HashMap需要我们加入额外的同步操作。
4、使用的hashcode不一样
Hashtable是直接使用的key的hashcode(key.hashcode())。而HashMap的key的hashcode是另外计算的。hashMap 独立了hash算法,并且算法是通过key value 多次算出来的,减少了重复性
5、HashMap允许有一个key为null,多个value为null。而Hashtable不允许key和value为null。
6、HashMap和Hashtable内部遍历方式的实现不一样
Hashtable、HashMap都使用了 Iterator。而由于历史原因,Hashtable还使用了Enumeration的方式 。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值