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

  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HashMap、Hashtable和HashSet是Java中常用的集合类。 HashMap和Hashtable都实现了Map接口,用于存储键值对。它们的主要区别在于线程安全性和同步性。HashMap是非线程安全的,而Hashtable是线程安全的。这意味着多个线程可以同时访问Hashtable,但不能同时访问HashMap。此外,HashMap允许存储null键值对,而Hashtable不允许。Java 5引入的ConcurrentHashMap可以作为Hashtable的替代,它在扩展性方面更好。 HashSet实现了Set接口,用于存储无序、不重复的元素。它底层使用HashMap来存储数据,HashSet存储对象而不存储键值对。 总结一下,HashMap和Hashtable都是用于存储键值对的,区别在于线程安全性和同步性。HashSet是用于存储不重复元素的集合。 引用: HashMap和Hashtable都实现了Map接口,主要的区别有:线程安全性,同步(synchronization),以及速度。HashMap几乎可以等价于Hashtable,除了HashMap是非synchronized的,并可以接受null(HashMap可以接受为null的键值(key)和值(value),而Hashtable则不行)。 HashMap是非synchronized,而Hashtable是synchronized,意味着Hashtable是线程安全的,多个线程可以共享一个Hashtable;而多个线程是不能共享HashMap的。Java 5提供了ConcurrentHashMap,它是HashTable的替代,比HashTable的扩展性更好。另一个区别是HashMap的迭代器(Iterator)是fail-fast迭代器,而Hashtable的enumerator迭代器。 HashMap可以通过下面的语句进行同步:Map m = Collections.synchronizeMap(hashMap); 引用:HashMap和Hashtable两个类都实现了Map接口,二者保存K-V对(key-value对);HashSet则实现了Set接口,性质类似于集合。 引用:HashSet:散列表,无序的,不会记录插入的顺序,实现了 Set 接口,以对象作为元素,拒绝接受重复的对象,底层依靠 HashMap来存储数据, 底层使用HashTable来保证元素的不重复性,实际上使用的是HashMap的一个实例。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [java集合HashMap、HashTable、HashSet详解](https://blog.csdn.net/weixin_38166557/article/details/99230114)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [浅析Java中Map与HashMap,Hashtable,HashSet的区别](https://download.csdn.net/download/weixin_38570296/12813847)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Java:HashMap、HashSet、HashTable](https://blog.csdn.net/weixin_48493408/article/details/123465326)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值