java数据结构源码解读——Hashtable

都说hashtable是已经被弃用的数据结构,大多时候会使用并发性能更好的CurrentHashMap。

但是作为面试常考的数据结构,在这里主要就了解一下。

我们看除了方法的部分应该是:

public class Hashtable<K,V>
    extends Dictionary<K,V>
    implements Map<K,V>, Cloneable, java.io.Serializable {
   private transient Entry<?,?>[] table;
private transient int count;
private int threshold;
private float loadFactor;
 private transient int modCount = 0;
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//methods.....
}

能看出Hashtable并不存在树化优化,其他的貌似差不多,但是Dictionary是我们从没见过的,怀着好奇的心思去看看:

public abstract
class Dictionary<K,V> {

    public Dictionary() {
    }


    public abstract int size();

    public abstract boolean isEmpty();


    public abstract Enumeration<K> keys();

    public abstract Enumeration<V> elements();

    public abstract V get(Object key);

  

    public abstract V put(K key, V value);


    public abstract V remove(Object key);
}

看上去和map有点像哈,但是既然是一堆空方法我们就放心了,直接看构造器!

 

    public Hashtable(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal Load: "+loadFactor);

        if (initialCapacity==0)
            initialCapacity = 1;
        this.loadFactor = loadFactor;
        table = new Entry<?,?>[initialCapacity];
        threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
    }
 public Hashtable(int initialCapacity) {
        this(initialCapacity, 0.75f);
    }
public Hashtable() {
        this(11, 0.75f);
    }

所以根据构造器我们可以得出和HashMap的几点区别:

1、默认的容量是11,而HashMap是16。

2、数组表是一旦创建就构造,属于饿汉模式,而HashMap是在第一次put时的resize构造。

 

看看put方法:

    public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {//不允许值是null的
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        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;
    }
    private void addEntry(int hash, K key, V value, int index) {
        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;
        }

        // Creates the new entry.
        @SuppressWarnings("unchecked")
        Entry<K,V> e = (Entry<K,V>) tab[index];
        tab[index] = new Entry<>(hash, key, value, e);//头插
        count++;
        modCount++;
    }

哦天呐,这都什么啊,和优雅的HashMap一比,简直不堪入目。

我们通过这里面的一些过程可以得到一些与HashMap的区别:

1、HashMap采用尾插法,就是先扫描过去然后插到尾部;而Hashtable采用头插法,先扫描确认新节点不存在于链表中,然后通过重新构造,把新节点插到头部。

2、线程安全?仅仅是put方法前面带有synchronize!

3、键值均不允许是null的,这个前面已经说过。

然后这一段是rehash的过程:

    protected void rehash() {
        int oldCapacity = table.length;
        Entry<?,?>[] oldMap = table;

        // overflow-conscious code
        int newCapacity = (oldCapacity << 1) + 1;
        if (newCapacity - MAX_ARRAY_SIZE > 0) {
            if (oldCapacity == MAX_ARRAY_SIZE)
                // Keep running with MAX_ARRAY_SIZE buckets
                return;
            newCapacity = MAX_ARRAY_SIZE;
        }
        Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];

        modCount++;
        threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
        table = newMap;

        for (int i = oldCapacity ; i-- > 0 ;) {
            for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
                Entry<K,V> e = old;
                old = old.next;

                int index = (e.hash & 0x7FFFFFFF) % newCapacity;
                e.next = (Entry<K,V>)newMap[index];
                newMap[index] = e;
            }
        }
    }

可以看出来扩容规则也不是一样的:Hashtable扩容公式是newCap=2*oldCap+1;而HashMa是2*oldCap;

然后并没有采用高位1分割链表算法(因为也不是偶数,不适用)。

而且迭代遍历是借助 Enumerator——枚举器来遍历,并不是HashMap那样的迭代器。

好了至此我们分析Hashtable已经完毕,剩下的没什么可说的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值