HashTable1.8源码分析

    HashTable是线程安全的用于键值对处理的数据类型,面试中也是经常出现,本文就以JDK1.8源码为例深入探讨HashTable的结构实现和功能原理。

类结构图

public class Hashtable extends Dictionary implements Map, Cloneable, Serializable


image.png

类注释

(1) HashTable实现Map接口继承Dictionary,不允许key或value为null(为null时抛出NPE)。
(2) 为了成功的存储、检索对象,作为键(key)的对象必须要实现hashCode和equals方法。
(3) 有两个参数会影响Hashtable的效率:一个是initial capacity(初始容量),一个是load factor(加载因子),HashTable运用拉链法(open hashing)处理hash冲突(hash collision),所谓拉链法就是当两个key的hash值相同时,放在同一个桶(buckets)中。
(4) 默认加载因子0.75是时间和空间的平衡,更高的加载因子可以更好的利用空间,但是对于元素操作[get|put]的效率会变低。
(5) 初始容量是空间浪费和耗时的rehash操作之间的权衡,如何hash表中元素数量大于初始容量乘加载因子时则需要执行rehash操作。
(6) 如果Hashtable中需要存放大量的元素,较高的hash容量会比因空间不足而自动进行的rehash操作更加高效。
(7) Hashtable是线程安全的。如果不需要线程安全推荐使用HashMap。如果需要高并发线程安全,则推荐使用ConcurrentHashMap。

实例变量

//hash表中用来存储数据(键值对)
private transient Entry[] table;

//hash表中元素的数量
private transient int count;

//扩容阀值(int)(capacity * loadFactor)
private int threshold;

//加载因子
private float loadFactor;

//hash表被修改[修改|删除]总次数,用来实现fail-fast机制
//fail-fast机制:所谓快速失败就是在并发集合中,进行迭代操作时若有其他线程对其进行结构性的修改,迭代器会立马感知到并且立即抛出异常,而不浪费时间和效率等待错误的发生,[抛出ConcurrentModificationException]
private transient int modCount = 0;

构造函数

//指定初始容量和加载因子构造一个新的哈希表
public Hashtable(int initialCapacity, float loadFactor) {
    //初始容量小于0
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
    //加载因子小于等于0或不是数字
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal Load: "+loadFactor);
    //初始容量最小为1
    if (initialCapacity==0)
        initialCapacity = 1;
    //设置加载因子
    this.loadFactor = loadFactor;
    //初始化哈希表数组大小,HashMap中初始化容量必须是2的幂,HashTable没有这个限制
    table = new Entry[initialCapacity];
    //初始化扩容阀值
    threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
}

//指定初始容量和默认的加载因子(0.75)构造一个新的哈希表
public Hashtable(int initialCapacity) {
    this(initialCapacity, 0.75f);
}

//默认构造函数,初始容量为11加载因子为0.75
public Hashtable() {
    this(11, 0.75f);
}

//构造一个与给定的Map具有相同映射关系的新哈希表
 public Hashtable(Map t) {
    //计算初始容量和加载因子,设置table大小
    this(Math.max(2*t.size(), 11), 0.75f);
    //将Map集合中的元素添加到HashTable中
    putAll(t);
}

Node是HashMap的一个内部类,实现了Map.Entry接口,每个黑色圆点就是一个Node对象。

private static class Entry implements Map.Entry {
    //数组索引位置
    final int hash;
    final K key;
    V value;
    //链表中下一个节点[单向链表]
    Entry next;

    protected Entry(int hash, K key, V value, Entry 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) next.clone()));
    }

    // Map.Entry Ops
    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;
    }

    //若两个Entry的键值对都相等时返回true
    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() {
        //调用Object类的[native]hashCode方法
        return hash ^ Objects.hashCode(value);
    }

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

HashTable.put(key, value) 插入方法

//使用synchronized关键字修饰方法
public synchronized V put(K key, V value) {
    // Make sure the value is not null
    //value为null抛出空指针,(如果key为null计算哈希值时会抛异常)
    if (value == null) {
        throw new NullPointerException();
    }
    // Makes sure the key is not already in the hashtable.
    //获取初始table
    Entry tab[] = table;
    //计算key的hashCode
    int hash = key.hashCode();
    //计算key的索引
    int index = (hash & 0x7FFFFFFF) % tab.length;
    @SuppressWarnings("unchecked")
    //生成Entry对象
    Entry entry = (Entry)tab[index];
    //迭代table数组
    for(; entry != null ; entry = entry.next) {
        //hash和key相等
        if ((entry.hash == hash) && entry.key.equals(key)) {
            //获取旧值
            V old = entry.value;
            //设置新值
            entry.value = value;
            //返回旧值
            return old;
        }
    }
    //添加新的Entry键值对
    addEntry(hash, key, value, index);
    //添加成功返回null
    return null;
}

//添加新的键值对
private void addEntry(int hash, K key, V value, int index) {
    //修改统计次数
    modCount++;
    //获取table数组
    Entry tab[] = table;
    //判断是否超过扩容阀值
    if (count >= threshold) {
        // Rehash the table if the threshold is exceeded
        //数组扩容
        rehash();
        tab = table;
        //计算hashCode
        hash = key.hashCode();
        //重新计算key的索引[扩容后,新的键值对在table中的位置可能发生变化]
        index = (hash & 0x7FFFFFFF) % tab.length;
    }
    // Creates the new entry.
    @SuppressWarnings("unchecked")
    //获取index位置上的链表
    Entry e = (Entry) tab[index];
    //采用"头插法",将Entry对象插入到HashTable的index位置上
    tab[index] = new Entry<>(hash, key, value, e);
    //hash表中元素的数量加1
    count++;
}

//数组扩容
@SuppressWarnings("unchecked")
protected void rehash() {
    //获取old哈希表容量
    int oldCapacity = table.length;
    Entry[] oldMap = table;

    // overflow-conscious code
    //新哈希表容量为原容量的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;

    //从尾部开始遍历
    for (int i = oldCapacity ; i-- > 0 ;) {
        //获取旧哈希表对应i位置上的链表
        for (Entry old = (Entry)oldMap[i] ; old != null ; ) {
            //对应i位置上的链表
            Entry e = old;
            //获取链表下个节点继续遍历
            old = old.next;
            // 获取在新哈希表中的位置
            int index = (e.hash & 0x7FFFFFFF) % newCapacity;
            //键值对逐个进行rehash()
            e.next = (Entry)newMap[index];
            //当前e做头节点
            newMap[index] = e;
        }
    }
}

//将Map的全部元素逐一添加到HashTable中
public synchronized void putAll(Map t) {
    for (Map.Entry e : t.entrySet())
        //调用put(K key, V value)方法
        put(e.getKey(), e.getValue());
}

HashTable.get(key) 查询方法

@SuppressWarnings("unchecked")
public synchronized V get(Object key) {
    //获取哈希表数组
    Entry tab[] = table;
    //计算key的hashCode
    int hash = key.hashCode();
    //计算key的索引
    int index = (hash & 0x7FFFFFFF) % tab.length;
    //遍历table数组
    for (Entry e = tab[index] ; e != null ; e = e.next) {
        //hash值和key都相等
        if ((e.hash == hash) && e.key.equals(key)) {
            //返回对应的value
            return (V)e.value;
        }
    }
    //不存在返回null
    return null;
}

HashTable.remove(key) 删除指定键值对方法

public synchronized V remove(Object key) {
    //获取table数组
    Entry tab[] = table;
    //计算key的hashCode
    int hash = key.hashCode();
    //计算key的索引
    int index = (hash & 0x7FFFFFFF) % tab.length;
    @SuppressWarnings("unchecked")
    //获取index位置上的链表
    Entry e = (Entry)tab[index];
    //在链表中找出要删除的节点,并删除该节点
    for(Entry prev = null ; e != null ; prev = e, e = e.next) {
        //hash值和key都相等
        if ((e.hash == hash) && e.key.equals(key)) {
            //修改统计次数
            modCount++;
            if (prev != null) {
                //指向待删除节点的下个节点
                prev.next = e.next;
            } else {
                //index索引位置指向next节点
                tab[index] = e.next;
            }
            //table中数量-1
            count--;
            //获取待删除key的value
            V oldValue = e.value;
            //清空value,方便GC
            e.value = null;
            //返回待删除key的value
            return oldValue;
        }
    }
    //不存在返回null
    return null;
}

HashTable.clear() 清空HashTable方法

public synchronized void clear() {
    //获取哈希表数组
    Entry tab[] = table;
    //修改统计次数
    modCount++;
    //从尾部开始遍历
    for (int index = tab.length; --index >= 0; )
        //清空table
        tab[index] = null;
    //哈希数组清空
    count = 0;
}

判断HashTable中是否包含指定的value

public synchronized boolean contains(Object value) {
    //value为null抛出空指针
    if (value == null) {
        throw new NullPointerException();
    }
    //初始化table数组
    Entry tab[] = table;
    //从尾部开始遍历
    for (int i = tab.length ; i-- > 0 ;) {
        //遍历指定index位置的链表
        for (Entry e = tab[i] ; e != null ; e = e.next) {
            //判断value是否存在
            if (e.value.equals(value)) {
                //存在返回true
                return true;
            }
        }
    }
    //不存在返回false
    return false;
}

//判断HashTable中是否包含指定的value
public boolean containsValue(Object value) {
    //调用contains(Object value)方法
    return contains(value);
}

判断HashTable中是否包含指定的key

public synchronized boolean containsKey(Object key) {
    //初始化table数组
    Entry tab[] = table;
    //获取key的hashCode
    int hash = key.hashCode();
    //计算key的index[hash&0x7FFFFFFF是避免负值的出现]
    int index = (hash & 0x7FFFFFFF) % tab.length;
    //遍历Entry对象
    for (Entry e = tab[index] ; e != null ; e = e.next) {
        //判断hash值和key是否相等
        if ((e.hash == hash) && e.key.equals(key)) {
            //存在返回true
            return true;
        }
    }
    //不存在返回false
    return false;
}

HashTable.size() 方法

public synchronized int size() {
    //返回table中元素数量
    return count;
}

//判断HashTable是否为空
public synchronized boolean isEmpty() {
    return count == 0;
}

其他方法

public synchronized Enumeration keys() {
    //返回所有key的枚举
    return this.getEnumeration(KEYS);
}

public synchronized Enumeration elements() {
    //返回所有value的枚举
    return this.getEnumeration(VALUES);
}

//克隆一个HashtTable,并返回Object对象
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);
    }
}

//返回一个被synchronizedSet封装后的KeySet对象,实现多线程同步
public Set keySet() {
    if (keySet == null)
        keySet = Collections.synchronizedSet(new KeySet(), this);
    return keySet;
}

//返回一个被synchronizedSet封装后的EntrySet对象,实现多线程同步
public Set> entrySet() {
    if (entrySet==null)
        entrySet = Collections.synchronizedSet(new EntrySet(), this);
    return entrySet;
 }

//若两个HashTable的所有键值对都相等时返回true
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 {
        //通过迭代器取出当前HashTable的键值对
        Iterator> i = entrySet().iterator();
        //若不相等则返回false,否则遍历完当前HashTable时返回true
        while (i.hasNext()) {
            Map.Entry 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;
}

//计算HashTable的哈希值
public synchronized int hashCode() {
    int h = 0;
    //若数组为0 或加载因子小于0返回0。
    if (count == 0 || loadFactor < 0)
        return h;  // Returns zero
    // Mark hashCode computation in progress
    loadFactor = -loadFactor;  
    Entry[] tab = table;
    for (Entry entry : tab) {
        while (entry != null) {
            //返回HashTable中的每个Entry的总和
            h += entry.hashCode();
            entry = entry.next;
        }
    }
    // Mark hashCode computation complete
    loadFactor = -loadFactor;  
    return h;
}

//将HashTable的"总的容量、实际容量、所有的Entry对象"都写入到输出流中
private void writeObject(java.io.ObjectOutputStream s) throws IOException {
    Entry 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的"总的容量、实际容量、所有的Entry"依次读出
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);

    int length = (int)((elements + elements / 20) / loadFactor) + 3;
    if (length > elements && (length & 1) == 0)
        length--;
    length = Math.min(length, origlength);

    if (length < 0) { // overflow
        length = origlength;
    }

    // Check Map.Entry[].class since it's the nearest public type to
    SharedSecrets.getJavaOISAccess().checkArray(s, Map.Entry[].class, length);
    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);
    }
}
以上为个人对HashTable1.8源码的总结。

你可能感兴趣的:(HashTable1.8源码分析)