【Java集合类源码分析】Hashtable源码分析

【Java集合类源码分析】Hashtable源码分析

一、Hashtable简介

    Hashtable是JDK1.0引入的,同样是基于哈希表(拉链法)实现的,每个元素都是一个key-value对,其内部通过单链表解决冲突,容量不足(超过了阈值)时,同样会进行扩容。

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

    Hashtable继承了Dictionary抽象类,实现了Map接口。
    Hashtable实现了实现了Cloneable接口,支持克隆;实现了Serializable接口,支持序列化,能够通过序列化传输。
    Hashtable线程安全,可在多线程环境下使用。

二、Hashtable源码分析

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

    /** * 存储数据的Entry数组。必要时调整大小 * Hashtable同样采用链表法解决冲突,每一个Entry本质上是一个单向链表 */
    private transient Entry<?,?>[] table;

    /** * Hashtable中包含的键值映射的数量 */
    private transient int count;

    /** * 阀值,用于判断是否需要调整Hashtable的容量(阀值=容量*加载因子) * @serial */
    private int threshold;

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

    /** * Hashtable被修改的次数,用于实现fail-fast机制 */
    private transient int modCount = 0;

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = 1421746759512286392L;


    /** * 构造具有指定的初始容量和加载因子的空HashMap * @param initialCapacity 初始容量 * @param loadFactor 加载因子 */
    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;
        //创建Entry数组
        table = new Entry<?,?>[initialCapacity];
        //设置阀值
        threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
    }

    /** * 构造具有指定初始容量和默认加载因子(0.75)的空Hashtable * @param initialCapacity 初始容量 */
    public Hashtable(int initialCapacity) {
        this(initialCapacity, 0.75f);
    }

   /** * 构造一个默认初始容量(11)和默认加载因子(0.75)空的Hashtable * 注意:Hashtable的默认初始容量为11,HashMap的默认初始容量为16 */
    public Hashtable() {
        this(11, 0.75f);
    }

    /** * 构造一个新的Hashtable包含指定的map */
    public Hashtable(Map<? extends K, ? extends V> t) {
        this(Math.max(2*t.size(), 11), 0.75f);
        putAll(t);
    }

    /** * 返回Hashtable中键值对的数量 */
    public synchronized int size() {
        return count;
    }

    /** * 如果Hashtable不包含键值对,则返回true */
    public synchronized boolean isEmpty() {
        return count == 0;
    }

    /** * 返回Hashtable中key的枚举对象 */
    public synchronized Enumeration<K> keys() {
        return this.<K>getEnumeration(KEYS);
    }

    /** * 返回Hashtable中value的枚举对象 */
    public synchronized Enumeration<V> elements() {
        return this.<V>getEnumeration(VALUES);
    }

    /** * 判断Hashtable是否包含指定value */
    public synchronized boolean contains(Object value) {
        if (value == null) {  //说明Hashtable中的value不能为null
            throw new NullPointerException();
        }

        Entry<?,?> tab[] = table;
        //从后向前遍历
        for (int i = tab.length ; i-- > 0 ;) {
            for (Entry<?,?> e = tab[i] ; e != null ; e = e.next) {
                if (e.value.equals(value)) {
                    return true;
                }
            }
        }
        return false;
    }

    /** * 判断Hashtable是否包含指定value */
    public boolean containsValue(Object value) {
        return contains(value);
    }

    /** * 判断Hashtable是否包含指定key */
    public synchronized boolean containsKey(Object key) {
        Entry<?,?> tab[] = table;
        //计算hash值(Hashtable直接用key的hashCode)
        int hash = key.hashCode();
        //计算索引值,hash值可能为负数,&0x7FFFFFFF是为了将负的hash值转化为正值
        int index = (hash & 0x7FFFFFFF) % tab.length;
        for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
            if ((e.hash == hash) && e.key.equals(key)) {
                return true;
            }
        }
        return false;
    }

    /** * 返回key对应的value,没有的话返回null */
    @SuppressWarnings("unchecked")
    public synchronized V get(Object key) {
        Entry<?,?> tab[] = table;
        //获取key的hashCode值
        int hash = key.hashCode();
        //根据hash值计算索引值以确定桶的位置
        int index = (hash & 0x7FFFFFFF) % tab.length;
        //遍历所在桶中的链表以查找键值等于key的元素
        for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
            //判断key是否相同
            if ((e.hash == hash) && e.key.equals(key)) {
                return (V)e.value;
            }
        }
        return null;
    }

    /** * 可分配的数组的最大大小 */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /** * 重新调整Hashtable的大小 * 当Hashtable中的键数达到其阈值时,将自动调用此方法 */
    @SuppressWarnings("unchecked")
    protected void rehash() {
        int oldCapacity = table.length;
        Entry<?,?>[] oldMap = table;

        //创建新容量大小的Entry数组(新容量=旧容量*2+1)
        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;

        //将旧Hashtable中的元素复制到新Hashtable中
        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;
                //重新计算索引值(重新组织各个Entry位置)
                int index = (e.hash & 0x7FFFFFFF) % newCapacity;
                e.next = (Entry<K,V>)newMap[index];
                newMap[index] = e;
            }
        }
    }

    /** * 向Hashtable中存储键值对 */
    public synchronized V put(K key, V value) {
        //Hashtable中不能插入value为null的元素
        if (value == null) {
            throw new NullPointerException();
        }

        Entry<?,?> tab[] = table;
        //获取key的hashCode值
        int hash = key.hashCode();
        //根据hash值计算索引值以确定桶的位置
        int index = (hash & 0x7FFFFFFF) % tab.length;
        //遍历所在桶中的链表以查找键值等于key的元素
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        for(; entry != null ; entry = entry.next) {
            //已存在,新value替换旧value,并返回旧value
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }

        //不存在,调用addEntry方法
        addEntry(hash, key, value, index);
        return null;
    }

    private void addEntry(int hash, K key, V value, int index) {
        modCount++;

        Entry<?,?> tab[] = table;
        //Hashtable实际容量超过了阀值
        if (count >= threshold) {
            // 重新调整Hashtable的大小(新容量为旧容量的两倍+1),并重新组织内部Entry
            rehash();

            tab = table;
            hash = key.hashCode();
            //扩容后重新计算索引值
            index = (hash & 0x7FFFFFFF) % tab.length;
        }

        //创建一个新的Entry<K,V>对象,然后添加到这个桶的链表头部
        @SuppressWarnings("unchecked")
        Entry<K,V> e = (Entry<K,V>) tab[index];
        tab[index] = new Entry<>(hash, key, value, e);
        count++;
    }

    /** * 删除键为key的元素,并返回value(如果存在) */
    public synchronized V remove(Object key) {
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> e = (Entry<K,V>)tab[index];
        //本质是删除单链表中的结点(单链表需要保留待删除结点的前一个结点)
        for(Entry<K,V> prev = null ; e != null ; prev = e, e = e.next) {
            if ((e.hash == hash) && e.key.equals(key)) {
                modCount++;
                if (prev != null) {
                    prev.next = e.next;
                } else {
                    tab[index] = e.next;
                }
                count--;
                V oldValue = e.value;
                e.value = null;
                return oldValue;
            }
        }
        return null;
    }

    /** * 将t中的全部元素都添加到Hashtable中 */
    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());
    }

    /** * 清空Hashtable,将Entry数组中的元素设为null */
    public synchronized void clear() {
        Entry<?,?> tab[] = table;
        modCount++;
        for (int index = tab.length; --index >= 0; )
            tab[index] = null;
        count = 0;
    }

    /** * 返回Hashtable实例的浅副本,键和值本身不会克隆 */
    public synchronized Object clone() {
        try {
            Hashtable<?,?> t = (Hashtable<?,?>)super.clone();
            t.table = new Entry<?,?>[table.length];
            for (int i = table.length ; i-- > 0 ; ) {
                t.table[i] = (table[i] != null)
                    ? (Entry<?,?>) table[i].clone() : null;
            }
            t.keySet = null;
            t.entrySet = null;
            t.values = null;
            t.modCount = 0;
            return t;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

    public synchronized String toString() {
        int max = size() - 1;
        if (max == -1)
            return "{}";

        StringBuilder sb = new StringBuilder();
        Iterator<Map.Entry<K,V>> it = entrySet().iterator();

        sb.append('{');
        for (int i = 0; ; i++) {
            Map.Entry<K,V> e = it.next();
            K key = e.getKey();
            V value = e.getValue();
            sb.append(key   == this ? "(this Map)" : key.toString());
            sb.append('=');
            sb.append(value == this ? "(this Map)" : value.toString());

            if (i == max)
                return sb.append('}').toString();
            sb.append(", ");
        }
    }

    /** * 获取Hashtable的枚举类对象 * 若Hashtable的实际大小为0,则返回"空枚举类"对象 * 否则,返回正常Enumerator对象 */
    private <T> Enumeration<T> getEnumeration(int type) {
        if (count == 0) {
            return Collections.emptyEnumeration();
        } else {
            return new Enumerator<>(type, false);
        }
    }

    /** * 获取Hashtable的迭代器、 * 若Hashtable的实际大小为0,则返回"空迭代器"对象 * 否则,返回正常Enumerator对象(Enumerator实现了迭代器和枚举两个接口) */
    private <T> Iterator<T> getIterator(int type) {
        if (count == 0) {
            return Collections.emptyIterator();
        } else {
            return new Enumerator<>(type, true);
        }
    }

    /** 返回key对应的集合,不能重复 */
    private transient volatile Set<K> keySet;
    /** 返回entrySet对应的集合,不能重复 */
    private transient volatile Set<Map.Entry<K,V>> entrySet;
    /** 返回value对应的集合,能够重复 */
    private transient volatile Collection<V> values;

    /** * 返回一个被synchronizedSet封装后的KeySet对象 * synchronizedSet封装的目的是对KeySet的所有的方法都添加synchronized,实现多线程同步 */
    public Set<K> keySet() {
        if (keySet == null)
            keySet = Collections.synchronizedSet(new KeySet(), this);
        return keySet;
    }

    /** * 返回key对应的集合 * KeySet继承于AbstractSet,该集合中没有重复的key */
    private class KeySet extends AbstractSet<K> {
        public Iterator<K> iterator() {
            return getIterator(KEYS);
        }
        public int size() {
            return count;
        }
        public boolean contains(Object o) {
            return containsKey(o);
        }
        public boolean remove(Object o) {
            return Hashtable.this.remove(o) != null;
        }
        public void clear() {
            Hashtable.this.clear();
        }
    }

    /** * 返回一个被synchronizedSet封装后的EntrySet对象 * synchronizedSet封装的目的是对EntrySet的所有的方法都添加synchronized,实现多线程同步 */
    public Set<Map.Entry<K,V>> entrySet() {
        if (entrySet==null)
            entrySet = Collections.synchronizedSet(new EntrySet(), this);
        return entrySet;
    }

    /** * 返回Entry对应的集合 * EntrySet继承于AbstractSet,该集合中没有重复的EntrySet */
    private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public Iterator<Map.Entry<K,V>> iterator() {
            return getIterator(ENTRIES);
        }

        public boolean add(Map.Entry<K,V> o) {
            return super.add(o);
        }

        public boolean contains(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> entry = (Map.Entry<?,?>)o;
            Object key = entry.getKey();
            Entry<?,?>[] tab = table;
            int hash = key.hashCode();
            int index = (hash & 0x7FFFFFFF) % tab.length;

            for (Entry<?,?> e = tab[index]; e != null; e = e.next)
                if (e.hash==hash && e.equals(entry))
                    return true;
            return false;
        }

        public boolean remove(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> entry = (Map.Entry<?,?>) o;
            Object key = entry.getKey();
            Entry<?,?>[] tab = table;
            int hash = key.hashCode();
            int index = (hash & 0x7FFFFFFF) % tab.length;

            @SuppressWarnings("unchecked")
            Entry<K,V> e = (Entry<K,V>)tab[index];
            for(Entry<K,V> prev = null; e != null; prev = e, e = e.next) {
                if (e.hash==hash && e.equals(entry)) {
                    modCount++;
                    if (prev != null)
                        prev.next = e.next;
                    else
                        tab[index] = e.next;

                    count--;
                    e.value = null;
                    return true;
                }
            }
            return false;
        }

        public int size() {
            return count;
        }

        public void clear() {
            Hashtable.this.clear();
        }
    }

    /** * 返回一个被synchronizedSet封装后的ValueCollection对象 * synchronizedSet封装的目的是对ValueCollection的所有的方法都添加synchronized,实现多线程同步 */
    public Collection<V> values() {
        if (values==null)
            values = Collections.synchronizedCollection(new ValueCollection(),
                                                        this);
        return values;
    }

    private class ValueCollection extends AbstractCollection<V> {
        public Iterator<V> iterator() {
            return getIterator(VALUES);
        }
        public int size() {
            return count;
        }
        public boolean contains(Object o) {
            return containsValue(o);
        }
        public void clear() {
            Hashtable.this.clear();
        }
    }

    // Comparison and hashing

    /** * 覆写equals函数 */
    public synchronized boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Map))
            return false;
        Map<?,?> t = (Map<?,?>) o;
        if (t.size() != size())
            return false;

        try {
            Iterator<Map.Entry<K,V>> i = entrySet().iterator();
            while (i.hasNext()) {
                Map.Entry<K,V> e = i.next();
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(t.get(key)==null && t.containsKey(key)))
                        return false;
                } else {
                    if (!value.equals(t.get(key)))
                        return false;
                }
            }
        } catch (ClassCastException unused)   {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }

        return true;
    }

    /** * 覆写hashCode函数 */
    public synchronized int hashCode() {
        int h = 0;
        if (count == 0 || loadFactor < 0)
            return h;  // Returns zero

        loadFactor = -loadFactor;  // Mark hashCode computation in progress
        Entry<?,?>[] tab = table;
        for (Entry<?,?> entry : tab) {
            while (entry != null) {
                h += entry.hashCode();
                entry = entry.next;
            }
        }

        loadFactor = -loadFactor;  // Mark hashCode computation complete

        return h;
    }

    /** * 将Hashtable实例的状态保存到流中(即序列化) */
    private void writeObject(java.io.ObjectOutputStream s)
            throws IOException {
        Entry<Object, Object> entryStack = null;

        synchronized (this) {
            // Write out the threshold and loadFactor
            s.defaultWriteObject();

            // Write out the length and count of elements
            s.writeInt(table.length);
            s.writeInt(count);

            // Stack copies of the entries in the table
            for (int index = 0; index < table.length; index++) {
                Entry<?,?> entry = table[index];

                while (entry != null) {
                    entryStack =
                        new Entry<>(0, entry.key, entry.value, entryStack);
                    entry = entry.next;
                }
            }
        }

        // Write out the key/value objects from the stacked entries
        while (entryStack != null) {
            s.writeObject(entryStack.key);
            s.writeObject(entryStack.value);
            entryStack = entryStack.next;
        }
    }

    /** * 从流中重构Hashtable实例(即反序列化) */
    private void readObject(java.io.ObjectInputStream s)
         throws IOException, ClassNotFoundException
    {
        // Read in the threshold and loadFactor
        s.defaultReadObject();

        // Validate loadFactor (ignore threshold - it will be re-computed)
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new StreamCorruptedException("Illegal Load: " + loadFactor);

        // Read the original length of the array and number of elements
        int origlength = s.readInt();
        int elements = s.readInt();

        // Validate # of elements
        if (elements < 0)
            throw new StreamCorruptedException("Illegal # of Elements: " + elements);

        // Clamp original length to be more than elements / loadFactor
        // (this is the invariant enforced with auto-growth)
        origlength = Math.max(origlength, (int)(elements / loadFactor) + 1);

        // Compute new length with a bit of room 5% + 3 to grow but
        // no larger than the clamped original length. Make the length
        // odd if it's large enough, this helps distribute the entries.
        // Guard against the length ending up zero, that's not valid.
        int length = (int)((elements + elements / 20) / loadFactor) + 3;
        if (length > elements && (length & 1) == 0)
            length--;
        length = Math.min(length, origlength);
        table = new Entry<?,?>[length];
        threshold = (int)Math.min(length * loadFactor, MAX_ARRAY_SIZE + 1);
        count = 0;

        // Read the number of elements and then all the key/value objects
        for (; elements > 0; elements--) {
            @SuppressWarnings("unchecked")
                K key = (K)s.readObject();
            @SuppressWarnings("unchecked")
                V value = (V)s.readObject();
            // sync is eliminated for performance
            reconstitutionPut(table, key, value);
        }
    }

    private void reconstitutionPut(Entry<?,?>[] tab, K key, V value)
        throws StreamCorruptedException
    {
        if (value == null) {
            throw new java.io.StreamCorruptedException();
        }
        // Makes sure the key is not already in the hashtable.
        // This should not happen in deserialized version.
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
            if ((e.hash == hash) && e.key.equals(key)) {
                throw new java.io.StreamCorruptedException();
            }
        }
        // Creates the new entry.
        @SuppressWarnings("unchecked")
            Entry<K,V> e = (Entry<K,V>)tab[index];
        tab[index] = new Entry<>(hash, key, value, e);
        count++;
    }

    /** * Entry<K,V>是单向链表,是Hashtable<K,V>的组织形式 */
    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;
        }

        @SuppressWarnings("unchecked")
        protected Object clone() {
            return new Entry<>(hash, key, value,
                                  (next==null ? null : (Entry<K,V>) next.clone()));
        }

        public K getKey() {
            return key;
        }

        public V getValue() {
            return value;
        }

        public V setValue(V value) {
            if (value == null)
                throw new NullPointerException();

            V oldValue = this.value;
            this.value = value;
            return oldValue;
        }

        public boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;

            return (key==null ? e.getKey()==null : key.equals(e.getKey())) &&
               (value==null ? e.getValue()==null : value.equals(e.getValue()));
        }

        public int hashCode() {
            return hash ^ Objects.hashCode(value);
        }

        public String toString() {
            return key.toString()+"="+value.toString();
        }
    }

    // Types of Enumerations/Iterations
    private static final int KEYS = 0;
    private static final int VALUES = 1;
    private static final int ENTRIES = 2;

    /** * Enumerator的作用是提供 * 通过elements()遍历Hashtable的接口 * 通过entrySet()遍历Hashtable的接口 */
    private class Enumerator<T> implements Enumeration<T>, Iterator<T> {
        Entry<?,?>[] table = Hashtable.this.table;
        int index = table.length;
        Entry<?,?> entry;
        Entry<?,?> lastReturned;
        int type;

        /** * Enumerator是迭代器(Iterator)还是枚举类(Enumeration)的标志 * true:迭代器;false:枚举类 */
        boolean iterator;

        /** * 在将Enumerator当作迭代器使用时会用到,用来实现fail-fast机制(检测并发修改) */
        protected int expectedModCount = modCount;

        Enumerator(int type, boolean iterator) {
            this.type = type;
            this.iterator = iterator;
        }

        /** * 判断是否存在下一个元素 * 从遍历table的数组的末尾向前查找,直到找到不为null的Entry */
        public boolean hasMoreElements() {
            Entry<?,?> e = entry;
            int i = index;
            Entry<?,?>[] t = table;
            /* Use locals for faster loop iteration */  
            while (e == null && i > 0) {
                e = t[--i];
            }
            entry = e;
            index = i;
            return e != null;
        }

        /** * 获取下一个元素 * 从后向前遍历数组,若某位置不为null(即所对应的单链表的头结点不为null),则遍历该单链表 */
        @SuppressWarnings("unchecked")
        public T nextElement() {
            Entry<?,?> et = entry;
            int i = index;
            Entry<?,?>[] t = table;
            /* Use locals for faster loop iteration */
            while (et == null && i > 0) {
                et = t[--i];
            }
            entry = et;
            index = i;
            if (et != null) {
                Entry<?,?> e = lastReturned = entry;
                entry = e.next;
                return type == KEYS ? (T)e.key : (type == VALUES ? (T)e.value : (T)e);
            }
            throw new NoSuchElementException("Hashtable Enumerator");
        }

        // Iterator methods
        public boolean hasNext() {
            return hasMoreElements();
        }

        public T next() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            return nextElement();
        }

        public void remove() {
            if (!iterator)
                throw new UnsupportedOperationException();
            if (lastReturned == null)
                throw new IllegalStateException("Hashtable Enumerator");
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();

            synchronized(Hashtable.this) {
                Entry<?,?>[] tab = Hashtable.this.table;
                int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length;

                @SuppressWarnings("unchecked")
                Entry<K,V> e = (Entry<K,V>)tab[index];
                for(Entry<K,V> prev = null; e != null; prev = e, e = e.next) {
                    if (e == lastReturned) {
                        modCount++;
                        expectedModCount++;
                        if (prev == null)
                            tab[index] = e.next;
                        else
                            prev.next = e.next;
                        count--;
                        lastReturned = null;
                        return;
                    }
                }
                throw new ConcurrentModificationException();
            }
        }
    }
}

三、总结

    1、Hashtable的容量为任意正整数(默认容量为11),而HashMap的容量始终为2的整数次幂(默认容量为16),两者的默认加载因子都是0.75。
    2、Hashtable中key和value都不允许为null(会抛NullPointerException异常),而HashMap中key和value都允许为null(key只能有一个为null,而value可以有多个为null)。
    3、扩容时,Hashtable的新容量为旧容量的2倍加1,而HashMap的新容量为旧容量的2倍
    4、Hashtable直接使用了key的hashCode(),而HashMap重新计算了key的hash值。Hashtable在计算索引时,先将hash值与上0x7FFFFFFF,这是为了保证hash值始终为正数(只有符号位改变,而后面的位都不变),再对数组长度取模,而HashMap使用的是h&(length-1),用位与运算代替取模提高了效率
    5、Hashtable不仅支持Iterator迭代器遍历而且支持Enumeration遍历。
    6、“Hashtable和HashMap的区别主要是前者是同步的,后者是快速失败机制保证不会出现多线程并发错误(Fast-Fail)。”,这是一个被很多文章转载过的概念,但其描述并不准确,容易引起误会。实质上,Fast-Fail与同步保护的是两种不同情况下的并发,两者不能拿来做比较。
    Hashtable是同步的,在执行get,put,remove,size,clear等一次性读写操作时,使用了同步机制,避免了多个线程同时读写Hashtable。但同步机制并不能避免在Iterator或Enumeration遍历过程中其他线程对Hashtable的put、remove、clear操作,这些写操作都会被毫无阻拦地成功执行。
    快速失败机制主要目的在于使Iterator遍历数组的线程能及时发现其他线程对Map的修改(如put、remove、clear等),因此,Fast-Fail并不能保证所有情况下的多线程并发错误,只能保护Iterator遍历过程中的iterator.next()与写并发。
    其次,Hashtable的iterator遍历方式也是支持Fast-Fail的,不能说它没有快速失败机制。写一个简单的例程就可以证明这一点,一个线程做Iterator遍历,另一个线程向Hashtable中put新的key和value,很容易就会观察到Fast-Fail机制报告ConcurrentModificationException。

    原文作者:java集合源码分析
    原文地址: https://blog.csdn.net/qq_18495465/article/details/71487312
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞