HashMap和HashTable

关于这个问题真的是老生常谈,面试题基本上必考,那么就来通过源码理解下两者的异同。

HashMap

Hash table based implementation of the <tt>Map</tt> interface.  This implementation provides all of the optional map operations, and permits <tt>null</tt> values and the <tt>null</tt> key.

建立在哈希表上对Map接口的实现,允许空的键和值。

The <tt>HashMap</tt> class is roughly equivalent to <tt>Hashtable</tt>, except that it is unsynchronized and permits nulls

(正是因为这句话所有好多人喜欢拿来和HashTable比较,其实很多面试题都是从源码中问的),HashMap和HashTable大致相同,但是HashMap是不同步的(也就意味着是线程不安全的),允许空值的。

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time

HashMap不能保证存储顺序

HashTable

This class implements a hash table, which maps keys to values. Any non-<code>null</code> object can be used as a key or as a value. 

任何非 null 对象都可以用作键或值。

Unlike the new collection implementations, {@code Hashtable} is synchronized.  If a thread-safe implementation is not needed, it is recommended to use{@link HashMap} in place of {@code Hashtable}.  If a thread-safe highly-concurrent implementation is desired, then it is recommended to use {@link java.util.concurrent.ConcurrentHashMap} in place of{@code Hashtable}.

HashTable是线程同步的,如果不需要实现线程安全,推荐使用HashMap替代HashTabl;如果需要线程安全以及高并发,推荐使用ConcurrentHashMap替代HashTable(真的,HashTable估计是开发者最后悔写的类,不然的话不会对HashMap做并发线程安全扩展而不对HashTable做)

HashTable如何实现线程安全呢?

让大家失望了,HashTable源码中找不到带有“Thread”的线程,它只是将每个方法声明成了synchronized 来保证线程同步,个人觉得HashTable=HashMap+synchronized 。

public synchronized int size();

public synchronized boolean isEmpty()

public synchronized boolean contains(Object value)

最核心的还是HashMap类

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

HashMap的底层实现靠的是这个Node类,这是一个单链表

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> 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;
        }
    }
这个方法也是put的根方法,我们看源码有点懵逼

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

对源码进行部分省略:

if ((p = tab[i = (n - 1) & hash]) == null)
//没有发生哈希碰撞(想创建Array[7]元素发现没有创建过,美滋滋~)
            tab[i] = newNode(hash, key, value, null);
        else {//已经存在了Array[7],没办法只能在这里增加一个链表了
            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 {//如果不是树节点,发现超过7个元素就转成红黑树
                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;
                }
            }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值