JDK源码解读十五章:java.util.Hashtable

275 阅读4分钟

Hashtable

1.Hashtable声明

    public class Hashtable<K,V>
    extends Dictionary<K,V>
    implements Map<K,V>, Cloneable, java.io.Serializable {}
    
    //键值对/Entry数组,每个Entry本质上是一个单向链表的表头
    private transient Entry<?,?>[] table;

    //当前表中的Entry数量,如果超过了阈值,就会扩容,即调用rehash方法
    private transient int count;

    //rehash阈值
    private int threshold;

    //负载因子
    private float loadFactor;

    //HashMap的数据被修改的次数,这个变量用于迭代过程中的Fail-Fast机制,其存在的意义在于保证发生了线程安全问题时,能及时的发现(操作前备份的count和当前modCount不相等)并抛出异常终止操作。
    private transient int modCount = 0; 

和HashMap一样,Hashtable 也是一个散列表,它存储的内容是键值对(key-value)映射。 Hashtable 继承于Dictionary,实现了Map、Cloneable、java.io.Serializable接口

2.构造方法

   //可指定初始容量和加载因子的构造方法
   public Hashtable(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal Load: "+loadFactor);

        if (initialCapacity==0)
            initialCapacity = 1;
        //赋值负载因子
        this.loadFactor = loadFactor;
        //创建键值对对象
        table = new Entry<?,?>[initialCapacity];
        //最大阈值不超过整数最大大小-8+1
        threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
    }

    //可指定初始容量和加载因子默认为0.75的构造方法
    public Hashtable(int initialCapacity) {
        this(initialCapacity, 0.75f);
    }

    //指定初始容量11和加载因子默认为0.75的构造方法
    public Hashtable() {
        this(11, 0.75f);
    }

    //包含子Map的构造函数,可以看到容量大小为map的2被大小,或者不超过11为11,调用putall方法存值,这个方法后面会学习到。
    public Hashtable(Map<? extends K, ? extends V> t) {
        this(Math.max(2*t.size(), 11), 0.75f);
        putAll(t);
    }
  • Hashtable的默认容量为11,默认负载因子为0.75.(HashMap默认容量为16,默认负载因子也是0.75)
  • Hashtable的容量可以为任意整数,最小值为1,而HashMap的容量始终为2的n次方。
  • 跟HashMap一样,Hashtable内部也有一个静态类叫Entry,其实是个键值对对象,保存了键和值的引用。

3.put(K key, V value)

   public synchronized V put(K key, V value) {
        // 如果value为空,直接抛出异常,这里可以看到hashtable是不允许null存在的
        if (value == null) {
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        //计算key所在的hash值并取余得到hash桶位置,明显这里和hashMap比较少了右移16,所以hashMap是做过优化的,hashtable现在用的很少了。
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        //遍历链表  
        for(; entry != null ; entry = entry.next) {
            //若键和hash值相同,则新值覆盖旧值
            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++
        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++;
    }
    
    protected void rehash() {
        //记录旧容量
        int oldCapacity = table.length;
        /记录旧的桶数组
        Entry<?,?>[] oldMap = table;

        //新容量为原容量的2倍+1,这里和hashMap是不一样的
        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;
            }
        }
    }
    
    //遍历map调用put插入数据
    public synchronized void putAll(Map<? extends K, ? extends V> t) {
        for (Map.Entry<? extends K, ? extends V> e : t.entrySet())
            put(e.getKey(), e.getValue());
    }
  • 插入的新节点总是在链表头。
  • 扩容数组大小是原来的2倍加1,还有一点比较重要扩容时插入新元素采用的是头插法,元素会进行倒序。

4.get(Object key)

   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;
    }
  • get操作比较简单,通过key的hash值遍历链表进行查找,找到立即返回,未找到则返回null。

5.总结

hashTable其实和hashMap差不多的,结构也相对简单就不在一一的分析了。这里说下hashMap和hashTable的区别:

  • hashTable是线程安全的,保证了同步,hashMap不保证线程安全。
  • hashTable不可以存放null值和null键,hashMap可以有一个null键,多个null值。
  • hashTable默认大小是11,扩容是2倍+1,hashMap默认大小是16,扩容是2的n次幂。