HashTable

Map 接口中,key 和 value 都可以为 null。

HashTable 实现中,key 和 value 都不允许为 null。

我们看一下它添加元素的方法:

    public synchronized V put(K key, V value) {
        if (value == null) { // value 不能为 null
            throw new NullPointerException();
        }
        Entry<?,?> tab[] = table;
        int hash = key.hashCode(); // key 不能为 null
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        for(; entry != null ; entry = entry.next) { // 添加新 Entry 的复杂度为 O(n)
            if ((entry.hash == hash) && entry.key.equals(key)) {  // 如果 hash 值已经存在,则用新值覆盖旧值
                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++;
        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;
        }
        @SuppressWarnings("unchecked")
        Entry<K,V> e = (Entry<K,V>) tab[index];
        tab[index] = new Entry<>(hash, key, value, e);  // 如果 hash 冲突,则插到队列头。
        count++;
    }
    private transient Entry<?,?>[] table;

 从代码中我们可以看出以下几点:

1. key 和 value 都不能为 null。

2. 添加新 Entry 的复杂度为 O(n)。

3. 如果 key 已经存在,则直接覆盖。

4. 如果 hash 冲突,就插到队列头部。不插到尾部,因为插到头部效率更高。

我们可以看一下 Entry 类:

    private static class Entry<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Entry<K,V> next;

        protected Entry(int hash, K key, V value, Entry<K,V> next) {
            this.hash = hash;
            this.key =  key;
            this.value = value;
            this.next = next;
        }
        ...

Entry 本质上就是一个单向链表的节点。

另外,HashTable 是同步的,除了构造函数意外,它的每个共有方法都是同步的:

1. 被 synchronized 修饰:

    1.1. 直接修饰:

public synchronized V put(K key, V value)

    1.2 间接修饰 :

    public boolean containsValue(Object value) {
        return contains(value);
    }
    public synchronized boolean contains(Object value)

2. 返回 synchronized 版本的集合:

    public Set<K> keySet() {
        if (keySet == null)
            keySet = Collections.synchronizedSet(new KeySet(), this);
        return keySet;
    }

 

总结:

1. HashTable 基于数组 + 链表实现。插入元素的复杂度为 O(n)。

2. HashTable 的 key 和 value 都不允许为 null。

3. HashTable 是同步的。

 

参考链接:

1. https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值