JDK 1.8 Hashtable的源码分析

    /**
     * Hashtable特点:
     *  与hashTable一样 1.1 效率低,线程安全,key 不为null  hashMap1.2  效率高,key为null 长度11
     */
public class Hashtable<K,V>
    extends Dictionary<K,V>
    implements Map<K,V>, Cloneable, java.io.Serializable {

    /**
     *hash表中的数据 table
     */
    private transient Entry<?,?>[] table;

    /**
     * 集合大小
     */
    private transient int count;

    /**
     * 重设大小的阈值 12
     */
    private int threshold;

    /**
     * 加载因子
     *
     * @serial
     */
    private float loadFactor;


// 初始值 长度11  加载因子0.75
    public Hashtable() {
        this(11, 0.75f);
    }
    
//  线程安全
    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;
    }
}
   
posted @ 2023-01-18 17:15  李悠然  阅读(10)  评论(0编辑  收藏  举报