Hashtable源码分析

释放双眼,带上耳机,听听看~!

文章目录

  • 简介
  • 类继承关系
  • 属性
  • 内部类
  • 构造方法
  • 添加方法put
  • 扩容
  • 获取get
  • 移除remove
  • 总结

简介

是hash表的一个实现,和HashMap大致相同,存储键值对,任何非空的数据可以作为key或者value。用作key的对象必须实现hashCode和equals方法。
数据结构为:数组+链表。
Hashtable是同步的。 如果不需要线程安全的实现,建议使用HashMap代替Hashtable 。 如果需要线程安全的并发实现,那么建议使用ConcurrentHashMap代替Hashtable 。

类继承关系

Hashtable源码分析
实现Map接口,继承Dictionary

属性


1
2
3
4
5
6
7
8
1    private transient Entry<?,?>[] table;//hash表数据
2    private transient int count;//数据总数
3    private int threshold;//扩容阈值
4    private float loadFactor;//负载因子
5    private transient int modCount = 0;//hash表结构修改次数
6    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//hash表最大数组长度
7
8

内部类


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1private static class Entry<K,V> implements Map.Entry<K,V> {
2    final int hash;
3    final K key;
4    V value;
5    Entry<K,V> next;//单链表
6    
7    protected Entry(int hash, K key, V value, Entry<K,V> next) {
8        this.hash = hash;
9        this.key =  key;
10        this.value = value;
11        this.next = next;
12    }
13}
14
15

构造方法


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
1//构造一个空的散列表,默认初始容量(11)和负载因子(0.75)。
2public Hashtable() {
3    this(11, 0.75f);
4}
5public Hashtable(int initialCapacity) {
6    this(initialCapacity, 0.75f);
7}
8public Hashtable(int initialCapacity, float loadFactor) {
9    if (initialCapacity < 0)
10        throw new IllegalArgumentException("Illegal Capacity: "+
11                                           initialCapacity);
12    if (loadFactor <= 0 || Float.isNaN(loadFactor))
13        throw new IllegalArgumentException("Illegal Load: "+loadFactor);
14
15    if (initialCapacity==0)
16        initialCapacity = 1;
17    this.loadFactor = loadFactor;
18    table = new Entry<?,?>[initialCapacity];//hashtable容量就是给定的容量
19    threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
20}
21
22

添加方法put


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
1 public synchronized V put(K key, V value) {
2    // Make sure the value is not null
3    if (value == null) {
4        throw new NullPointerException();
5    }
6
7    //确认key不在hash表中
8    Entry<?,?> tab[] = table;
9    int hash = key.hashCode();
10    // 这里hash & 0x7FFFFFFF之后得到hash本身 没作用
11    // hash % tab.length之后 得到hash表低位 小于tab.lenth的一位数
12    // 取与之后得到一个小于长度的数字
13    int index = (hash & 0x7FFFFFFF) % tab.length;
14    Entry<K,V> entry = (Entry<K,V>)tab[index];
15    for(; entry != null ; entry = entry.next) {
16        if ((entry.hash == hash) && entry.key.equals(key)) {
17            V old = entry.value;
18            entry.value = value;
19            return old;
20        }
21    }
22  //如果没有冲突 那就构造新节点加入
23    addEntry(hash, key, value, index);
24    return null;
25}
26
27private void addEntry(int hash, K key, V value, int index) {
28    modCount++;//修改次数
29
30    Entry<?,?> tab[] = table;
31    //是否需要扩容
32    if (count >= threshold) {
33        rehash();//扩容table
34        tab = table;
35        hash = key.hashCode();
36        index = (hash & 0x7FFFFFFF) % tab.length;//计算新的位置
37    }
38
39    Entry<K,V> e = (Entry<K,V>) tab[index];
40    tab[index] = new Entry<>(hash, key, value, e);//头插法
41    count++;
42}
43
44

扩容


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
1protected void rehash() {
2    int oldCapacity = table.length;
3    Entry<?,?>[] oldMap = table;
4
5    // 扩容规则:扩容一倍再加一
6    int newCapacity = (oldCapacity << 1) + 1;
7    if (newCapacity - MAX_ARRAY_SIZE > 0) {
8        if (oldCapacity == MAX_ARRAY_SIZE)
9            // Keep running with MAX_ARRAY_SIZE buckets
10            return;
11        newCapacity = MAX_ARRAY_SIZE;
12    }
13    Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];
14
15    modCount++;
16    threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
17    table = newMap;
18
19  //双层for循环遍历 外层遍历hash槽 内层遍历链表
20    for (int i = oldCapacity ; i-- > 0 ;) {
21        for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
22            Entry<K,V> e = old;
23            old = old.next;
24          //计算每个数据新的槽位 放入对应槽位的链表
25            int index = (e.hash & 0x7FFFFFFF) % newCapacity;
26            e.next = (Entry<K,V>)newMap[index];
27            newMap[index] = e;
28        }
29    }
30}
31
32

获取get


1
2
3
4
5
6
7
8
9
10
11
12
13
1public synchronized V get(Object key) {
2    Entry<?,?> tab[] = table;
3    int hash = key.hashCode();
4    int index = (hash & 0x7FFFFFFF) % tab.length;
5    for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
6        if ((e.hash == hash) && e.key.equals(key)) {
7            return (V)e.value;
8        }
9    }
10    return null;
11}
12
13

移除remove


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
1public synchronized V remove(Object key) {
2    Entry<?,?> tab[] = table;
3    int hash = key.hashCode();
4    int index = (hash & 0x7FFFFFFF) % tab.length;//定位
5    Entry<K,V> e = (Entry<K,V>)tab[index];
6    for(Entry<K,V> prev = null ; e != null ; prev = e, e = e.next) {
7       //循环链表找到数据 注意:hashcode不想等 对象必定不想等、hashcode相等 对象有可能相等
8        if ((e.hash == hash) && e.key.equals(key)) {
9            modCount++;
10            if (prev != null) {
11                prev.next = e.next;
12            } else {
13                tab[index] = e.next;
14            }
15            count--;
16            V oldValue = e.value;
17            e.value = null;
18            return oldValue;
19        }
20    }
21    return null;
22}
23
24

总结

Hashtable线程安全,但是不推荐使用
Hashtable数据结构 数组+链表
定位使用hashcode % 数组长度,有别于hashmap的hashcode & 数组长度-1但是结果一样,注意比对

给TA打赏
共{{data.count}}人
人已打赏
安全经验

Google AdSense 全面发挥贵网站的创收潜力

2021-10-11 16:36:11

安全经验

安全咨询服务

2022-1-12 14:11:49

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索