本次分析代码为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;
}

最新文章

  1. UNIX网络编程——getsockname和getpeername函数
  2. Objective-C Polymorphism
  3. 获取iframe外边数据
  4. hdu 5233 Gunner II
  5. json化表单数据
  6. [C语言 - 6] static &amp; extern
  7. linux下passwd命令设置修改用户密码
  8. Spring Http Invoker
  9. 图数据库之Pregel
  10. Linux 下安装配置 JDK1.7
  11. cron expr
  12. Android的cookie的接收和发送
  13. IDEA无法创建类,接口
  14. URLEncoder 和URLDecoder
  15. NgDL:第四周深层神经网络
  16. CSS: Position Introduction.
  17. IOS初级:AFNetworking
  18. rocketmq 学习记录-2
  19. Ubuntu-14.04.1 desktop安装时及安装后遇到的小问题
  20. jquery 隐藏 显示 动画效果

热门文章

  1. 获取IIS版本
  2. jquery ajax promise
  3. Delphi流的操作
  4. 国产数据库-KingbaseES在linux下的安装
  5. 扩展BaseAdapter实现不存储列表项的ListView
  6. 有关extdelete恢复测试
  7. 在Winfrom下实现类似百度、Google搜索自能提示功能
  8. 如何改变xls中的单元格左上角的图标
  9. AngularJS的五个超酷特性
  10. Log4j与common-logging联系与区别