一、概述
和HashMap一樣,Hashtable 也是一個(gè)散列表,它存儲(chǔ)的內(nèi)容是鍵值對(duì)(key-value)映射。
繼承于Dictionary,實(shí)現(xiàn)了Map、Cloneable、java.io.Serializable接口。
二、數(shù)據(jù)結(jié)構(gòu)
拉鏈法:數(shù)組+鏈表,和HashTable一樣
三、特點(diǎn)
- 線程安全
- 不容許null值
- 無序
- Iterator是fail-fast的
四、實(shí)現(xiàn)要點(diǎn)
1. 基本實(shí)現(xiàn)
和hashMap一致
2. hash相關(guān)
hashMao一致
3. 訪問方式
提供兩種訪問方式:
Enumeration
Dictionary定義接口返回Enumeration<E>,返回Enumerator(type = KEYS/value = VALUES)
Iterator
Dictionary定義接口返回Enumeration<E>,返回Enumerator(type = KEYS/value = VALUES)
Enumerator
實(shí)現(xiàn)了Enumeration、Iterator接口,實(shí)現(xiàn)原理和HashMap中Iterator一樣
當(dāng)元素為空時(shí)
返回Collections.emptyEnumeration()或者Collections.emptyIterator()
public static <T> Iterator<T> emptyIterator() {
return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR;
}
private static class EmptyIterator<E> implements Iterator<E> {
static final EmptyIterator<Object> EMPTY_ITERATOR
= new EmptyIterator<>();
public boolean hasNext() { return false; }
public E next() { throw new NoSuchElementException(); }
public void remove() { throw new IllegalStateException(); }
@Override
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
}
}
4. null值處理
在public方法時(shí)進(jìn)行判斷,key/value為null時(shí)拋出NullPointerException
5. 線程安全實(shí)現(xiàn)方式
三點(diǎn):
- public方法添加同步鎖synchronized
- 返回視圖時(shí)使用Collections.synchronizedSet
- Iterator中方法加同步鎖synchronized