源码之HashTable

构造函数

   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);
    }

        public Hashtable(Map<? extends K, ? extends V> t) {
        this(Math.max(2*t.size(), 11), 0.75f);
        putAll(t);
    }

分析:
Hashtable(int initialCapacity, float loadFactor)构造函数默认容量是11,加载因子(负载因子)0.75,如果第四个构造函数,那么就取2*size与11更大的那个作为初始容量。我们知道HashMap的容量一定是2整数次幂,用的初始容量为16,HashTable为啥用11为默认初始容量?我们先带着这个问题继续往下看。

Put方法

    public synchronized void putAll(Map<? extends K, ? extends V> t) {
        for (Map.Entry<? extends K, ? extends V> e : t.entrySet())
            put(e.getKey(), e.getValue());
    }

        public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == 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) {
        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;
        }

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

        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;
            }
        }
    }

分析:
int index = (hash & 0x7FFFFFFF) % tab.length;这句话是做什么用的呢?(hash & 0x7FFFFFFF) 的&位运算是为了确保是一个正整数,而hash是一个有符号数。如果hash值相同,那么再去比较key是不是相等,如果相等那么替换old值,并返回old值。如果没有找到相同的key,那么说明不同的key发生了碰撞,那么就利用链地址法解决这个问题,把新元素连接到该index后面的尾部。在连接到index后面之前,是否进行扩容的判断,如果达到临界值,那么进行扩容,一旦扩容之后需要重新构建hash表,int newCapacity = (oldCapacity << 1) + 1;这句表示扩容后的大小(2n+1),然后把原来的hashtable值拷贝到新hashtable中,从这里我们就可以看出,hashtable选用的就是通过利用奇数作为容量,那么这么做是否能够让元素分布更加均匀呢?如果有知道的同学可以跟我分析你的看法。

总结:
1.HashTable是线程安全的
2.HashTable底层实现跟HashMap一样,使用的是链表数组。
3.HashTable的扩容公式是:2n+1,默认容量11或者2*size,选用奇数作为容量。
4.HashTable中没有hash函数了,直接取的是Object.hashCode值作为hash值
5.HashTable中没有再做类似HashMap中的扰动来降低碰撞概率

猜你喜欢

转载自blog.51cto.com/4837471/2309817