10-Hashtable底层结构和源码分析

介绍汇总:

  1. Hashtable的基本介绍
  2. Hashtable底层机制说明
  3. Hashtable 和 HashMap 对比

1-Hashtable的基本介绍

  1. 存放的元素是键值对:即 K-V
  2. Hashtable 的键和值都不能为 null ,不然后抛出 NullPointerException 异常
  3. Hashtable 使用方法基本上和 HashMap 一样
  4. Hashtable 是线程安全的,HashMap 是线程不安全的

2-Hashtable底层机制说明

  1. Hashtable 中维护的是数组+链表,来进行数据存储
  2. Hashtable 初始化

注:从初始流程图中,可以发现在初始化时就创建好内部维护的数组、扩容警戒值、装载因子。默认初始的初始容量为 11 ,以及默认的装载因子为 0.75。

  1. 添加元素

注:其中每次扩容都会以原本容量的 2 倍 + 1 为新容量,newCapacity = (oldCapacity << 1) + 1;,还有就是索引的取法为 (hash & 0x7FFFFFFF) % tab.length;,反正就是按位与、完了取余,长度为当前对应数组的长度或容量。

  1. 扩容实践练习
// 扩容一
package map.hashtable;

import java.util.Hashtable;

public class HashtableSource {

    @SuppressWarnings({"all"})
    public static void main(String[] args) {

        Hashtable hashtable = new Hashtable();

        for (int i = 1 ; i <= 18 ; i ++ ) {
            hashtable.put(i,i) ;
        }
    }
}

// 扩容二
package map.hashtable;

import java.util.Hashtable;

public class HashtableIncrement {

    @SuppressWarnings({"all"})
    public static void main(String[] args) {

        Hashtable hashtable = new Hashtable();

        for (int i = 1 ; i <= 20 ; i ++ ) {
            hashtable.put(new Person(i),1) ;
        }
    }
}

class Person {

    private int i ;

    public Person(int i) {
        this.i = i;
    }

    @Override
    public int hashCode() {
        return 100;
    }

    @Override
    public String toString() {
        return "Person{" +
                "i=" + i +
                '}';
    }
}

3-Hashtable 和 HashMap 对比

Map 版本 线程安全 效率 语序 null 键 null 值
HashMap 1.2 不安全 可以
Hashtable 1.0 安全 较低 不可以