HashMap和Hashtable的区别

HashMap和Hashtable的区别

1、线程安全

Hashtable是线程安全的,HashMap不是线程安全的

Hashtable所有的元素操作都是synchronized修饰的,而HashMap并没有

2、性能优劣

Hashtable是线程安全的,每个方法都要阻塞其他线程,所以Hashtable性能较差,HashMap性能较好,使用更广

如果要线程安全又要保证性能,建议使用JUC包下的ConcurrentHashMap

3、NULL

Hashtable是不允许键或值为null的,HashMap的键值则都可以为null

Hashtable代码片段

    public synchronized V put(K key, V value) {
        // 如果value为null,直接抛出空指针异常
        if (value == null) {
            throw new NullPointerException();
        }
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        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;
    }

HashMap代码片段

    static final int hash(Object key) {
        int h;
        // key为null做了特殊处理
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

4、实现方式

Hashtable继承源码

public class Hashtable<K,V>
    extends Dictionary<K,V>
    implements Map<K,V>, Cloneable, java.io.Serializable {

HashMap继承源码

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {

Hashtable继承了Dictionary,而HashMap继承了AbstractMap

5、容量扩容

HashMap的初始容量为16,Hashtable初始容量为11,两者的负载因子默认都是0.75

Hashtable代码片段

    public Hashtable() {
        this(11, 0.75f);
    }

HashMap代码片段

    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

当现有容量大于总容量*负载因子时,HashMap扩容规则为当前容量翻倍,Hashtable扩容规则为当前容量翻倍+1

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

邋遢的流浪剑客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值