一、概述
和HashMap一样,Hashtable 也是一个散列表,它存储的内容是键值对(key-value)映射。
继承于Dictionary,实现了Map、Cloneable、java.io.Serializable接口。
二、数据结构
拉链法:数组+链表,和HashTable一样
三、特点
- 线程安全
- 不容许null值
- 无序
- Iterator是fail-fast的
四、实现要点
1. 基本实现
和hashMap一致
2. hash相关
hashMao一致
3. 访问方式
提供两种访问方式:
Enumeration
Dictionary定义接口返回Enumeration<E>,返回Enumerator(type = KEYS/value = VALUES)
Iterator
Dictionary定义接口返回Enumeration<E>,返回Enumerator(type = KEYS/value = VALUES)
Enumerator
实现了Enumeration、Iterator接口,实现原理和HashMap中Iterator一样
当元素为空时
返回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方法时进行判断,key/value为null时抛出NullPointerException
5. 线程安全实现方式
三点:
- public方法添加同步锁synchronized
- 返回视图时使用Collections.synchronizedSet
- Iterator中方法加同步锁synchronized
网友评论