认识 Hashtable!
Hashtable<K,V> 定义:
- public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, Serializable - 实现哈希表!
Hashtable<K,V> 特点:
- 1.key与value俱都不能为null;
- 2.Hashtable是同步的,所有方法都被synchronized修饰,性能低下;
- 3.因为同时访问hash表的线程只能有一个,伸缩性不好;
- 4.Hashtable紧紧保证了对单个方法的调用是线程安全的.但仍然存在潜在的线程安全隐患.
- 实际上,对每个方法都用 synchronized 修饰,仍然不足以保证线程安全性.因为当我们使用混合操作时仍然需要偶外的同步.
- 比如put-if-absent(空则放入),或如下代码所示的迭代(可能因为fail-fast机制导致 ConcurrentModificationException).
- Hashtable<String,String> hash = new Hashtable<String,String>();
if(hash.containsKey("key")){
//假设进入该条件语句后,键为key的entry被其他线程remove.
Set<String> keySet = hash.keySet();
for(Iterator<String> it = keySet.iterator();it.hasNext();){
String next = it.next();//fail-fast
}
} - 5.在使用size()方法进行循环时,当进入最后一次循环时,可能因为有其他线程对哈希表做了remove操作,导致 NullPointerException.
- 6.针对迭代器的fail-fast机制.
Hashtable<K,V> 构造函数:
- public java.util.Hashtable(int arg-0);
public java.util.Hashtable();
public java.util.Hashtable(interface java.util.Map arg-0);
public java.util.Hashtable(int arg-0,float arg-1); - 无参构造方法调用其他构造方法创建一个初始容量为11,加载因子为0.75f的哈希表。/**
* Constructs a new, empty hashtable with a default initial capacity (11)
* and load factor (0.75).
*/
public Hashtable() {
this(11, 0.75f);
} - public Hashtable(int initialCapacity, float loadFactor) {
if (initialCapacity < 0) //哈希表初始容量不能小于0.
throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
if (loadFactor <= 0 || Float.isNaN(loadFactor)) //哈希表默认加载因子是大于0的数字.
throw new IllegalArgumentException("Illegal Load: " + loadFactor);
if (initialCapacity==0)//若初始容量为0,则取实际容量为1
initialCapacity = 1;
this.loadFactor = loadFactor;
table = new Entry[initialCapacity];
threshold = (int)(initialCapacity * loadFactor);//哈希表包含的entry的数量不小于该值时,哈希表将扩容.
} Hashtable<K,V> 包含方法:
- public synchronized class java.lang.Object get(class java.lang.Object arg-0);
public synchronized class java.lang.Object put(class java.lang.Object arg-0,class java.lang.Object arg-1);
public synchronized boolean equals(class java.lang.Object arg-0);
public synchronized class java.lang.String toString();
public interface java.util.Collection values();
public synchronized int hashCode();
public synchronized class java.lang.Object clone();
public synchronized void clear();
public synchronized boolean contains(class java.lang.Object arg-0);
public synchronized boolean isEmpty();
public interface java.util.Set entrySet();
public synchronized void putAll(interface java.util.Map arg-0);
public synchronized int size();
public synchronized class java.lang.Object remove(class java.lang.Object arg-0);
public synchronized interface java.util.Enumeration elements();
public interface java.util.Set keySet();
public synchronized interface java.util.Enumeration keys();
public synchronized boolean containsKey(class java.lang.Object arg-0);
public boolean containsValue(class java.lang.Object arg-0);
public final native void wait(long arg-0)throws java.lang.InterruptedException;
public final void wait()throws java.lang.InterruptedException;
public final void wait(long arg-0,int arg-1)throws java.lang.InterruptedException;
public final native class java.lang.Class getClass();
public final native void notify();
public final native void notifyAll(); 方法分析:
public synchronized class java.lang.Object put(class java.lang.Object arg-0,class java.lang.Object arg-1);添加成功则返回null,若实际做了替换操作,则返回被替换掉的value.- /*** 将指定KEY映射到该哈希表中指定VALUE!* Maps the specified <code>key</code> to the specified
* <code>value</code> in this hashtable. Neither the key nor the
* value can be <code>null</code>. <p>
*
* The value can be retrieved by calling the <code>get</code> method
* with a key that is equal to the original key.
*/
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) { //value不能为null
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry tab[] = table;
int hash = key.hashCode(); //key不能为null
int index = (hash & 0x7FFFFFFF) % tab.length;// 找到特定位置下的桶(bucket),bucket中的数据以链表的形式存储,遍历链表,寻找key对应的entryfor (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) { //找到该Key对应的Entry,则用新的value替换原有value
V old = e.value;
e.value = value;
return old; //返回旧Entry的value
}
}
modCount++; //hashtable被操作(增加,删除,替换,哈希表容量调整)的次数,通常用于Fail-fast机制的实现// count:The total number of entries in the hash table.哈希表包含entry的数量,不是指数组被使用的长度。// threshold: 用于标识Hashtable的容量是否需要扩展(threshold = 当前哈希表Entry[]数组长度*加载因子(默认0.75f))if (count >= threshold) {//原哈希表中不存在该key对应的entry,并且需扩展哈希表的容量
// Rehash the table if the threshold is exceeded
rehash();//哈希表容量扩展完成,重新设置tab的值,重新计算index的值
tab = table;
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
Entry<K,V> e = tab[index];//临时entry//每次创建新的entry,都将其置于table数组的特定位置,即将新增的entry作为哈希表中特定的桶的链表的头。//最近操作的entry有更多的可能被使用,将其置于链表的头部有助于提高查找效率。//也就是说将最近使用的对象放到离自己最近的地方。
tab[index] = new Entry<K,V>(hash, key, value, e);
count++;
return null;
} - /**
* Increases the capacity of and internally reorganizes this
* hashtable, in order to accommodate and access its entries more
* efficiently. This method is called automatically when the
* number of keys in the hashtable exceeds this hashtable's capacity
* and load factor.
*/
protected void rehash() {//原哈希表的容量
int oldCapacity = table.length;
Entry[] oldMap = table;//新哈希表的容量定义为原哈希表容量的2倍+1.
int newCapacity = oldCapacity * 2 + 1;
Entry[] newMap = new Entry[newCapacity];
modCount++;//fail-fast
threshold = (int)(newCapacity * loadFactor);
table = newMap;//遍历所有entries重新计算存储地址
for (int i = oldCapacity ; i-- > 0 ;) {
for (Entry<K,V> old = oldMap[i] ; old != null ; ) {
Entry<K,V> e = old;
old = old.next;
int index = (e.hash & 0x7FFFFFFF) % newCapacity;
e.next = newMap[index];
newMap[index] = e;
}
}
} - package com.collection.all;
import java.util.Hashtable;
/**
* 测试Hashtable的哈希表容量扩展时,包含的entries如何重新存储!
*/
public class Client {
public static void main(String[] args){
Client c = new Client();
c.test();
}
private void test(){
/**
* 哈希表容量扩展1次,则为11.若要使本来在一个桶里的entries,在哈希表容量扩展之后,仍旧处于一个桶中,
* 则应使Apples的num属性对5和11取余得到相同的值
*/
Hashtable<Apples,String> tab = new Hashtable<Apples,String>(5);
tab.put(new Apples(1), "");
tab.put(new Apples(56), "");
//哈希表容量扩展之后,12对11取余得1,应与前2个entry在同一个桶中.
tab.put(new Apples(12), "");
System.out.println(); //断点断点如图://容量扩展,对所有entry重新安排存储地址。再将111添加进去.
tab.put(new Apples(111), "");
//最终在哈希表tab[1]的位置:111指向1指向56指向12
System.out.println(); //断点断点如图:
}
class Apples {
private int num;
public Apples(int num){
this.num = num;
}
public int hashCode() {
return num;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Apples other = (Apples) obj;
if (num != other.num)
return false;
return true;
}
}
}
public synchronized void clear();- 将哈希表对应的数组每一项都设为null.
- /**
* Clears this hashtable so that it contains no keys.
*/
public synchronized void clear() {
Entry tab[] = table;
modCount++;//fail-fast
for (int index = tab.length; --index >= 0; )
tab[index] = null;
count = 0;
} - public synchronized boolean contains(class java.lang.Object arg-0);
- 判断哈希表中是否包含了映射到改value的key.
- public synchronized boolean contains(Object value) {
if (value == null) {
throw new NullPointerException();
}
Entry tab[] = table;
for (int i = tab.length ; i-- > 0 ;) {
for (Entry<K,V> e = tab[i] ; e != null ; e = e.next) {
if (e.value.equals(value)) {
return true;
}
}
}
return false;
} - public synchronized boolean containsKey(class java.lang.Object arg-0);
- 判断哈希表中是否包含改key.
- public synchronized boolean containsKey(Object key) {
Entry tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return true;
}
}
return false;
}
public boolean containsValue(class java.lang.Object arg-0);- 同 : public synchronized boolean contains(class java.lang.Object arg-0);
- public boolean containsValue(Object value) {
return contains(value);
} - public synchronized class java.lang.Object remove(class java.lang.Object arg-0);
- 从哈希表中移除该key对应的entry(使它的前一个entry指向它后一个entry).返回该entry的value.
- 若哈希表中不存在改key对应的entry,返回null.
- /**
* Removes the key (and its corresponding value) from this
* hashtable. This method does nothing if the key is not in the hashtable.
*/
public synchronized V remove(Object key) {
Entry tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<K,V> e = tab[index], 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;
}
public synchronized boolean isEmpty();- 判断该哈希表是否为空,根据表中entry的数量,而不是表的容量.
- /**
* Tests if this hashtable maps no keys to values.
*/
public synchronized boolean isEmpty() {
return count == 0;
} - public synchronized int size();
- 返回哈希表中entry的数量.
- /**
* Returns the number of keys in this hashtable.
*/
public synchronized int size() {
return count;
}
public synchronized class java.lang.String toString();- 打印出该哈希表包含的映射集合,形式如 {a=b, c=b}
- 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(", ");
}
}
public synchronized class java.lang.Object get(class java.lang.Object arg-0);- 若哈希表中包含该key对应的entry ,则返回value.否则返回null.
- public synchronized V get(Object key) {
Entry tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return e.value;
}
}
return null;
}
public synchronized class java.lang.Object clone();- 创建此哈希表的浅表副本。复制哈希表自身的所有结构,但不复制它的键和值。这是一个开销相对较大的操作。
- public synchronized Object clone() {
try {
Hashtable<K,V> t = (Hashtable<K,V>) super.clone();
t.table = new Entry[table.length];
for (int i = table.length ; i-- > 0 ; ) {
t.table[i] = (table[i] != null)
? (Entry<K,V>) 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();
}
} - public synchronized boolean equals(class java.lang.Object arg-0);
- public synchronized boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Map))
return false;
Map<K,V> t = (Map<K,V>) 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;
}
public synchronized int 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 (int i = 0; i < tab.length; i++)
for (Entry e = tab[i]; e != null; e = e.next)
h += e.key.hashCode() ^ e.value.hashCode();
loadFactor = -loadFactor; // Mark hashCode computation complete
return h;
}
public synchronized void putAll(interface java.util.Map arg-0);- 将传入Map包含的映射关系存储到当前哈希表.
- 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());
} - private static Enumeration emptyEnumerator = new EmptyEnumerator();
private static Iterator emptyIterator = new EmptyIterator();//使用内部类实现Iterator迭代器.这是一个针对空哈希表的迭代器
private static class EmptyIterator implements Iterator<Object> {
EmptyIterator() {
}
public boolean hasNext() {
return false;
}
public Object next() {
throw new NoSuchElementException("Hashtable Iterator");
}
public void remove() {
throw new IllegalStateException("Hashtable Iterator");
}
} - 内部类实现哈希表碰撞链表节点类
- /**
* Hashtable collision list.
*/
private static class Entry<K,V> implements Map.Entry<K,V> {
int hash;
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;
}
protected Object clone() {
return new Entry<K,V>(hash, key, value,
(next==null ? null : (Entry<K,V>) 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;
}
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 ^ (value==null ? 0 : value.hashCode());
}
public String toString() {
return key.toString()+"="+value.toString();
}
} - 定义内部工具类实现对哈希表的迭代和枚举,迭代功能(迭代器方法)调用枚举方法实现,多了fail-fast机制。
- // Types of Enumerations/Iterations
private static final int KEYS = 0;
private static final int VALUES = 1;
private static final int ENTRIES = 2;
/**
* A hashtable enumerator class. This class implements both the
* Enumeration and Iterator interfaces, but individual instances
* can be created with the Iterator methods disabled. This is necessary
* to avoid unintentionally increasing the capabilities granted a user
* by passing an Enumeration.
*/
private class Enumerator<T> implements Enumeration<T>, Iterator<T> {
Entry[] table = Hashtable.this.table;
int index = table.length;
Entry<K,V> entry = null;
Entry<K,V> lastReturned = null;
int type;
/**
* Indicates whether this Enumerator is serving as an Iterator
* or an Enumeration. (true -> Iterator).
*/
boolean iterator;
/**
* The modCount value that the iterator believes that the backing
* Hashtable should have. If this expectation is violated, the iterator
* has detected concurrent modification.
*/
protected int expectedModCount = modCount;
Enumerator(int type, boolean iterator) {
this.type = type;
this.iterator = iterator;
}
public boolean hasMoreElements() {
Entry<K,V> 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;
}
public T nextElement() {
Entry<K,V> 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<K,V> 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)//fail-fast
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;
for (Entry<K,V> e = tab[index], 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();
}
}
} - public synchronized interface java.util.Enumeration keys();
- 返回哈希表中key的枚举.
- private static final int KEYS = 0;//说明是key的枚举/**
* Returns an enumeration of the keys in this hashtable.
*/
public synchronized Enumeration<K> keys() {
return this.<K>getEnumeration(KEYS);
}
private <T> Enumeration<T> getEnumeration(int type) {
if (count == 0) {
return (Enumeration<T>)emptyEnumerator;
} else {
return new Enumerator<T>(type, false);
}
} - public synchronized interface java.util.Enumeration elements();
- 返回哈希表中值的枚举.
- private static final int VALUES = 1;
public synchronized Enumeration<V> elements() {
return this.<V>getEnumeration(VALUES);
}
private <T> Enumeration<T> getEnumeration(int type) {
if (count == 0) {
return (Enumeration<T>)emptyEnumerator;
} else {
return new Enumerator<T>(type, false);
}
} - public interface java.util.Set keySet();
- 返回哈希表中key的集合.
- private transient volatile Set<K> keySet = null;public Set<K> keySet() {
if (keySet == null)
keySet = Collections.synchronizedSet(new KeySet(), this);
return keySet;
}
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();
}
}
private <T> Iterator<T> getIterator(int type) {
if (count == 0) {
return (Iterator<T>) emptyIterator;
} else {
return new Enumerator<T>(type, true);
}
} - public interface java.util.Set entrySet();
- 返回此哈希表中碰撞链表节点的集合.
- private static final int ENTRIES = 2;
private transient volatile Set<Map.Entry<K,V>> entrySet = null;
public Set<Map.Entry<K,V>> entrySet() {
if (entrySet==null)
entrySet = Collections.synchronizedSet(new EntrySet(), this);
return 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<K,V> entry = (Map.Entry<K,V>) o;
K key = entry.getKey();
Entry[] tab = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<K,V> e = tab[index], 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();
}
}
private <T> Iterator<T> getIterator(int type) {
if (count == 0) {
return (Iterator<T>) emptyIterator;
} else {
return new Enumerator<T>(type, true);
}
} - public interface java.util.Collection values();
- 返回该哈希表value的Collection.
- Returns a {@link Collection} view of the values contained in this map.
- private static final int VALUES = 1;
private transient volatile Collection<V> values = null;
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();
}
}
private <T> Iterator<T> getIterator(int type) {
if (count == 0) {
return (Iterator<T>) emptyIterator;
} else {
return new Enumerator<T>(type, true);
}
}