HashTable源码分析

来源:互联网 发布:淘宝导购网站 编辑:程序博客网 时间:2024/05/23 17:05

  本次分析代码为JDK1.8中HashTable代码。
  HashTable不允许null作为key和value。
  HashTable中的方法为同步的,所以HashTable是线程安全的。

Entry类

介绍

  • Entry是HashTable内的一个静态内部类,实现了Map.Entry接口。table的类型就是Entry。

基本参数

  • hash:存这个Entry的hash值
  • key:存key值
  • value:存value的值
  • next:通过链表连接下一个Entry
final int hash;final K key;V value;Entry<K,V> next;

构造函数

  • 用来新建Entry,需要四个参数。
protected Entry(int hash, K key, V value, Entry<K,V> next) {    this.hash = hash;    this.key =  key;    this.value = value;    this.next = next;}

方法

  • getKey方法:返回key值
  • getValue方法:返回value的值
  • setValue方法:修改value值
  • 重写了equals和hashCode方法:hashCode方法通过计算该Entry的hash值与value的hash值进行异或运算;equals方法通过判断key和value是否同时相同来判断。
public int hashCode() {    return hash ^ Objects.hashCode(value);}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()));}

HashTable类

继承与实现

  • HashTable继承自Dictionary类,实现了Map接口。
public class Hashtable<K,V>    extends Dictionary<K,V>    implements Map<K,V>, Cloneable, java.io.Serializable

基本参数

  • HashTable中的数据存放在一个叫做table的数组中,类型为Entry,Entry实现了Map.Entry接口,Entry为HashTable的一个静态内部类。
  • count:entry总数。
  • loadFactor:负载因子。
  • threshold:临界值,当table的size超过临界值,就会进行rehash,这个值等于capacity * loadFactor。
    private transient Entry<?,?>[] table;    private transient int count;    private int threshold;    private float loadFactor;

构造函数

  • 默认的HashTable中table的大小为11,负载因子的默认值为0.75。
  • 可以指定初始table的大小,也可以指定loadFactor的大小,也可以将一个Map直接复制到本HashTable。

put方法

  • 同步方法。
  • hash值为key的hashCode。
  • index = (hash & 0x7FFFFFFF) % tab.length,新增的Entry的index值为key的hash值与0x7FFFFFFF求与再对table的长度求余。
  • 获取到table中下标为index的entry,若存在hash值和key值相同的entry,则用新值替换旧值,若不存在,则新增一个entry。
  • addEntry方法里,如果count大于等于threshold,则进行rehash,否则新增一个Entry,并将在index位置上的旧的Entry接到新增的Entry后。
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++;}

get方法

  • 同步方法。
  • 计算出key的hash值,并计算出table的下标index,然后对该链表进行遍历,若有相同者,则返回value的值,否则返回null。
public synchronized V get(Object key) {    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.key.equals(key)) {            return (V)e.value;        }    }    return null;}

rehash方法

  • 先进行扩容,新的容量为旧的容量的两倍再加一。
  • 让table指向容量为新值的新的数组。
  • 将旧的table中原有的值进行重新计算,重新计算出新的index,并将原来table中的链表连接到新的table中。
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;        }    }}

hashCode方法

  • 本方法是同步的。
  • 通过计算table中每一个Entry的hashCode之和作为返回值。
public synchronized int hashCode() {        /*         * This code detects the recursion caused by computing the hash code         * of a self-referential hash table and prevents the stack overflow         * that would otherwise result.  This allows certain 1.1-era         * applets with self-referential hash tables to work.  This code         * abuses the loadFactor field to do double-duty as a hashCode         * in progress flag, so as not to worsen the space performance.         * A negative load factor indicates that hash code computation is         * in progress.         */        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;    }



0 0
原创粉丝点击