HashTable详解

我们都知道 HashTable 与 HashMap 一样,也是以 数组+链表 的形式存储数据的,而最主要的区别是 HashTable 是绝对线程安全的。以下主要是对 HashTable 的底层原理做解析。

一、定义

1、HashTable 在 Java8 中的定义如下:

public class Hashtable<K,V>
    extends Dictionary<K,V>
    implements Map<K,V>, Cloneable, java.io.Serializable

从定义中可以看出 HashTable 继承 Dictionary 类,实现 Map、Cloneable、Serializable接口。

2、 HashTable 数据结构图如下:
HashTable数据结构

3、内部主要成员变量

   /**
     * The hash table data.
     */
    private transient Entry<?,?>[] table;

    /**
     * The total number of entries in the hash table.
     */
    private transient int count;

    /**
     * The table is rehashed when its size exceeds this threshold.  (The
     * value of this field is (int)(capacity * loadFactor).)
     *
     * @serial
     */
    private int threshold;

    /**
     * The load factor for the hashtable.
     * @serial
     */
    private float loadFactor;

    /**
     * The number of times this Hashtable has been structurally modified
     * Structural modifications are those that change the number of entries in
     * the Hashtable or otherwise modify its internal structure (e.g.,
     * rehash).  This field is used to make iterators on Collection-views of
     * the Hashtable fail-fast.  (See ConcurrentModificationException).
     */
    private transient int modCount = 0;
  • table:Entry[] 数组类型,实际上 Entry 是一个单向链表。每一个 Entry 都是一个键值对,哈希表的"key-value键值对"都是存储在 Entry 数组中的。
  • count:HashTable 的大小,它是Hashtable保存的键值对的数量(不是HashTable 容器的大小,是所有 Entry 键值对的总数)。
  • threshold:HashTable 容量的阈值,用于判断是否需要调整Hashtable的容量。threshold的值=“容量*加载因子”。
  • loadFactor:加载因子,默认0.75f。
  • modCount:HashTable 被改变的次数,用来实现 fail-fast 机制。

二、主要方法解析

1、put 方法
以下是基于 jdk1.8 的源码分析,源代码如下:

    public synchronized V put(K key, V value) {
        //①  确保 value 值不为空
        if (value == null) {
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
        // ② 计算key的hash值,直接使用 key.hashCode(),表明 key 不为空,否则也会 NPE
        int hash = key.hashCode();
        // ③ 确认 key 在 table[] 中的索引位置
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        // ④ 链式迭代查找逻辑,可以看出采用的数据结构是(数组 + 链表)
        for(; entry != null ; entry = entry.next) {
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }
	// 添加节点的入口
        addEntry(hash, key, value, index);
        return null;
    }

	private void addEntry(int hash, K key, V value, int index) {
        modCount++;

        Entry<?,?> tab[] = table;
        // ⑤ 当前的容量超过阈值,进行扩容操作
        if (count >= threshold) {
            // Rehash the table if the threshold is exceeded
            rehash();

            tab = table;
            hash = key.hashCode();
            // 根据扩容后的数组大小重新计算索引位置
            index = (hash & 0x7FFFFFFF) % tab.length;
        }

        // Creates the new entry.
        @SuppressWarnings("unchecked")
        Entry<K,V> e = (Entry<K,V>) tab[index];
        tab[index] = new Entry<>(hash, key, value, e);
        count++;
    }

具体的分析如下:
① 确保 value 值不为空。
② 计算key的hash值,直接使用 key.hashCode(),表明 key 不为空,否则也会 NPE。
③ 确认 key 在 table[] 中的索引位置,具体的算法是:key 的 hash 值去除最高为,然后和 table 的长度取余。
④ 链式迭代查找逻辑,可以看出采用的数据结构是(数组 + 链表)。
⑤ 当前的容量超过阈值,进行扩容操作,扩容的大小为:newCapacity = (oldCapacity << 1) + 1,即容量扩大两倍+1。

2、扩容方法

HashTable 进行 put 操作时,如果需要添加数据,会首先进行容量的校验,如果容量已经到达了阈值,HashTable 就会进行扩容处理 rehash(),具体的源码如下:

protected void rehash() {
	// 旧容量
        int oldCapacity = table.length;
        // 旧数组
        Entry<?,?>[] oldMap = table;

        // 新容量 = 旧容量 * 2 + 1
        int newCapacity = (oldCapacity << 1) + 1;
        if (newCapacity - MAX_ARRAY_SIZE > 0) {
            if (oldCapacity == MAX_ARRAY_SIZE)
                // Keep running with MAX_ARRAY_SIZE buckets
                return;
            newCapacity = MAX_ARRAY_SIZE;
        }
        // 创建一个新容量大小的数组
        Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];

        modCount++;
        // 重新计算阀值
        threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
        table = newMap;
	// 将旧数组的数据搬迁到新数组
        for (int i = oldCapacity ; i-- > 0 ;) {
            for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
                Entry<K,V> e = old;
                old = old.next;

                int index = (e.hash & 0x7FFFFFFF) % newCapacity;
                e.next = (Entry<K,V>)newMap[index];
                newMap[index] = e;
            }
        }
    }

在这个rehash()方法中我们可以看到容量扩大两倍+1,同时需要将原来HashTable中的元素一一复制到新的HashTable中,这个过程是比较消耗时间的,需要重新计算索引位置。

3、get 方法

相比于 put 方法,get 方法比较简单,计算 key 的 hash 值,然后判断在 table 中的索引位置,迭代链表后返回,具体的源码如下:

public synchronized V get(Object key) {
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
            if ((e.hash == hash) && e.key.equals(key)) {
                return (V)e.value;
            }
        }
        return null;
    }

参考:HashTable

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值