Java源码集合类Hashtable学习

古城微笑少年丶 2022-07-08 15:59 350阅读 0赞

Hashtable类简介

java version “1.7.0_67”

  1. Hashtable类继承了Dictionary抽象类,实现了MapCloneablejava.io.Serializable接口,它的底层实现原理和HashMap类是差不多的。Hashtable类最大的一个特点是:线程安全的,对外提供调用的方法都加了同步关键字Synchronized,但同时也降低了性能。插入的“键—值”都不能为null
  2. public class Hashtable<K,V>
  3. extends Dictionary<K,V>
  4. implements Map<K,V>, Cloneable, java.io.Serializable {

1.常用的构造方法HashTable(),默认初始化容量大小11,加载因子0.75

  1. /**
  2. * Constructs a new, empty hashtable with a default initial capacity (11)
  3. * and load factor (0.75).
  4. */
  5. public Hashtable() {
  6. this(11, 0.75f);
  7. }

2.HasTable中的put(K key, V value)方法,用了synchronized关键字保证线程安全

  1. public synchronized V put(K key, V value) {
  2. // Make sure the value is not null
  3. if (value == null) {
  4. //在HashTable中value不能为null,否则报空指针异常
  5. throw new NullPointerException();
  6. }
  7. // Makes sure the key is not already in the hashtable.
  8. Entry tab[] = table;
  9. int hash = hash(key);//key为null则会报空指针异常错误
  10. int index = (hash & 0x7FFFFFFF) % tab.length;
  11. for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
  12. //哈希码值相等并且key值也相等,就会把就的value值替换成新的value值
  13. if ((e.hash == hash) && e.key.equals(key)) {
  14. V old = e.value;
  15. e.value = value;
  16. return old;
  17. }
  18. }
  19. modCount++;
  20. //总数量大于等于阀值,那么就需要对数组进行扩容
  21. if (count >= threshold) {
  22. // Rehash the table if the threshold is exceeded
  23. rehash();
  24. tab = table;
  25. hash = hash(key);
  26. index = (hash & 0x7FFFFFFF) % tab.length;
  27. }
  28. // Creates the new entry.
  29. Entry<K,V> e = tab[index];
  30. //根据索引index处存入新的entry,并且把有一个next引用指向旧的entry
  31. //连着成一个链表,新插入的都是成为新的链表头
  32. tab[index] = new Entry<>(hash, key, value, e);
  33. count++;
  34. return null;
  35. }

可以看出hash(Object k)方法,计算哈希码值比较的简单,没有像HashMap中的那样做防碰撞处理。

  1. private int hash(Object k) {
  2. // hashSeed will be zero if alternative hashing is disabled.
  3. return hashSeed ^ k.hashCode();
  4. }

3.Hashtable 类中的内部类:Enumerator,实现了接口Enumeration和Iterator,主要的用途是对外提供迭代器和枚举器用于遍历Hashtable中的key和value值。

总结:

当前,Hashtable在实际应用中不常用了,多线程访问下被ConcurrentHashMap类所替代了,因为它的性能比Hashtable高。

发表评论

表情:
评论列表 (有 0 条评论,350人围观)

还没有评论,来说两句吧...

相关阅读