在上一篇中对List的实现类进行了总结,本应该学习Collection接口的另外一个子接口Set,但是由于
HashSet是基于HashMap、TreeSet是基于TreeMap。所以现将先对Map进行学习。
Map
Collection集合最大的特点是每次进行单个对象的保存,如果要对一对对象来进行保存,就只能够使用Map集合。
Map是一种把键对象和值对象映射的集合,它的每一个元素都包含一对键对象和值对象。
(即Map集合中会一次性保存两个对象,且这两个对象的关系:key=value结构。这种结构最大的特点是可以通过key找到对应的value内容。)
Map没有继承Collection接口
(1)AbstractMap:一个抽象类,实现了Map接口。Map的基本实现,其他Map实现类都可以通过
继承AbstractMap来减少代码的编写。
(2)SortedMap:继承自Map的一个接口。保证按照键的升序排列的映射。对entrySet、keySet和
values方法返回的结果进行迭代时,顺序就会范颖出来。
(3)NavigableMap:继承SortedMap,含有返回天剑最近匹配的导航方法。
(4)HashMap:继承自AbstractMap,实现Map接口。是Map接口基于哈希表的实现,
是使用频率最高的用于键值对处理的数据类型。大多数情况下可以直接定位到其值,
特别是访问速度快,遍历顺序不确定,线程不安全,最多允许一个key为null,
可允许对个value为null。可以使用Collections的synchronizedMap方法使得Map具有线程安全的能力,
或者使用ConcurrentHashMap.
(5)HashTable:HashTable和HashMap从存储结构和实现上有很多相似之处,不同的是它继承自Dictionary类,是线程安全的,
HashTable不允许key和value为null。并发性不如ConcurrentHashMap,因为ConcurrentHashMap引入了分段锁,
HashTable不建议在新的代码中使用,不需要线程安全的场合下建议使用HashMap,需要线程安全的场合使用ConcurrentHashMap。
(6)LinkedHashMap:LinkedHashMap继承自HashMap,是Map接口的哈希表和链接列表的实现,它维护了一个双重链接列表。此链接列表定义了迭代顺序,
该迭代顺序可以是插入顺序或者访问顺序。
(7)WeakedHashMap:以弱键实现的基于哈希表的Map,在WeakHashMap中,当某个键不再正常使用时,将自动移出其条目。
(8)TreeMap:Map接口基于红黑树的实现。
HashMap
HashMap和List最大的区别就是采用key-value形式对数据进行存储。至于如何保存和处理key-value键值对?接下来将对其进行分析。
底层数据结构
HashMap的底层数据结构在JDK1.8之前是数组+链表;在JDK1.8之后是数组+链表+红黑树。通常将数组中的每一个节点称为一个桶。
当给桶中添加一个键值对时,首先要计算键值对中key所对应的hash值,以此来确定要插入数组中的位置,但是可能存在同一个hash值
的元素被放在数组的同一个位置,这种现象称为碰撞,这时候若元素重复则不插入,若不重复则按照尾插法(在JDK1.8之前为头插法)
的方式添加key-value到同一个hash值的元素的后面,链表就是这样形成的。当链表长度超过8(TREEIFY_THRESHOLD)时,
链表就转化为红黑树。
如上图是HashMap在JDK1.8之前的结构图,左半边是哈希表,也称为哈希数组,数组的每一个元素都是单链表的头结点,
链表使用来解决hash冲突的(HashMap是利用链地址法解决哈希冲突的) ,如果不同的key映射到数组的同一个位置,
就将其放入单链表中(头插)。如果在一个链表中查找一个节点,就要花费O(n)的查找时间,会有很大的性能损失。
所以在JDK1.8后采用红黑树。
在上图中展示的是JDK1.8之后HashMap的结构图,可以清楚的看到数据结构有数组、链表、红黑树,
桶中的结构可以是链表也可以是红黑树,红黑树的引入是为了提高效率。
位桶
hashMap中的一个重要字段,table哈希桶数组,即一个Node的数组。
transient Node<K,V>[] table;
链表的实现
node中包含的next变量是链表的关键点,hash结果相同的元素就是通过这个next来进行关联的。
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value ;
Node<K,V> next;
Node(int hash, K key, V value , Node<K,V> next) {
this .hash = hash;
this .key = key;
this .value = value ;
this .next = next;
}
public final K getKey () { return key; }
public final V getValue () { return value ; }
public final String toString () { return key + "=" + value ; }
public final int hashCode () {
return Objects.hashCode(key) ^ Objects.hashCode(value );
}
public final V setValue (V newValue) {
V oldValue = value ;
value = newValue;
return oldValue;
}
public final boolean equals (Object o) {
if (o == this )
return true ;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value , e.getValue()))
return true ;
}
return false ;
}
}
红黑树的实现
红黑树与链表相比,多了四个变量,parent父节点,left左节点,right右节点,prev上一个统计节点.
static final class TreeNode <K ,V > extends LinkedHashMap .Entry <K ,V > {
TreeNode<K,V> parent;
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev;
boolean red;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super (hash, key, val, next);
}
final TreeNode<K,V> root() {
for (TreeNode<K,V> r = this , p;;) {
if ((p = r.parent) == null )
return r;
r = p;
}
}
在以上三种数据结构的基础上,我们就可以想到HashMap的实现了:首先有一个数组,当添加元素时(key-value),
首先计算元素key的hash值来确定要插入数组的位置,若存在同一个hash值的元素已经被放在数组的同一个位置了,
则需要将该元素添加值同一hash值元素的后面,他们在数组的同一个位置就形成了链表,所以说数组中存放的是链表,
当链表的长度太长(>8)时,链表就转化为红黑树,这样有利于提高查找效率。
构造函数
1.无参构造函数
构造一个默认初始容量为16,默认加载因子为0.75的空HashMap.
public HashMap () {
this .loadFactor = DEFAULT_LOAD_FACTOR;
}
2.指定初始化容量的构造函数
构造一个带有指定初始化容量和默认加载因子为0.75的构造函数。
public HashMap (int initialCapacity) {
this (initialCapacity, DEFAULT_LOAD_FACTOR);
}
3.指定初始化容量和加载因子的构造函数
构造一个带有指定初始化容量和指定加载因子的空HashMap.
public HashMap (int initialCapacity, float loadFactor) {
if (initialCapacity < 0 )
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this .loadFactor = loadFactor;
this .threshold = tableSizeFor(initialCapacity);
}
由构造方法可以看出影响HashMap性能的两个重要参数:初始化容量和加载因子。
部分源码
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4 ;
static final int MAXIMUM_CAPACITY = 1 << 30 ;
static final float DEFAULT_LOAD_FACTOR = 0.75 f;
static final int TREEIFY_THRESHOLD = 8 ;
static final int UNTREEIFY_THRESHOLD = 6 ;
static final int MIN_TREEIFY_CAPACITY = 64 ;
transient Node<K,V>[] table;
transient Set<Map.Entry<K,V>> entrySet;
transient int size;
transient int modCount;
int threshold;
final float loadFactor;
static final int hash(Object key) {
int h;
return (key == null ) ? 0 : (h = key.hashCode()) ^ (h >>> 16 );
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0 )
n = (tab = resize()).length;
if ((p = tab[i = (n - 1 ) & hash]) == null )
tab[i] = newNode(hash, key, value, null );
…………
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null ;
}
public V put (K key, V value) {
return putVal(hash(key), key, value, false , true );
}
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1 ) & hash]) != null ) {
Node<K,V> node = null , e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null ) {
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break ;
}
p = e;
} while ((e = e.next) != null );
}
}
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this , tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null ;
}
public V remove (Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null , false , true )) == null ?
null : e.value;
}
public void clear () {
Node<K,V>[] tab;
modCount++;
if ((tab = table) != null && size > 0 ) {
size = 0 ;
for (int i = 0 ; i < tab.length; ++i)
tab[i] = null ;
}
}
public boolean containsValue (Object value) {
Node<K,V>[] tab; V v;
if ((tab = table) != null && size > 0 ) {
for (int i = 0 ; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null ; e = e.next) {
if ((v = e.value) == value ||
(value != null && value.equals(v)))
return true ;
}
}
}
return false ;
}
public int size () {
return size;
}
public Set<K> keySet () {
Set<K> ks = keySet;
if (ks == null ) {
ks = new KeySet();
keySet = ks;
}
return ks;
}
final class KeySet extends AbstractSet<K> {
public final int size () { return size; }
public final void clear () { HashMap.this .clear(); }
public final Iterator<K> iterator () { return new KeyIterator(); }
public final boolean contains (Object o) { return containsKey(o); }
public final boolean remove (Object key) {
return removeNode(hash(key), key, null , false , true ) != null ;
}
public final Spliterator<K> spliterator () {
return new KeySpliterator<>(HashMap.this , 0 , -1 , 0 , 0 );
}
public final void forEach (Consumer<? super K> action) {
Node<K,V>[] tab;
if (action == null )
throw new NullPointerException();
if (size > 0 && (tab = table) != null ) {
int mc = modCount;
for (int i = 0 ; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null ; e = e.next)
action.accept(e.key);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
public Set<Map.Entry<K,V>> entrySet () {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public final int size () { return size; }
public final void clear () { HashMap.this .clear(); }
public final Iterator<Map.Entry<K,V>> iterator () {
return new EntryIterator();
}
public final boolean contains (Object o) {
if (!(o instanceof Map.Entry))
return false ;
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
Object key = e.getKey();
Node<K,V> candidate = getNode(hash(key), key);
return candidate != null && candidate.equals(e);
}
public final boolean remove (Object o) {
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
Object key = e.getKey();
Object value = e.getValue();
return removeNode(hash(key), key, value, true , true ) != null ;
}
return false ;
}
public final Spliterator<Map.Entry<K,V>> spliterator () {
return new EntrySpliterator<>(HashMap.this , 0 , -1 , 0 , 0 );
}
public final void forEach (Consumer<? super Map.Entry<K,V>> action) {
Node<K,V>[] tab;
if (action == null )
throw new NullPointerException();
if (size > 0 && (tab = table) != null ) {
int mc = modCount;
for (int i = 0 ; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null ; e = e.next)
action.accept(e);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
在JDK1.8 中重写的方法
public V getOrDefault (Object key, V defaultValue) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
}
public V putIfAbsent (K key, V value) {
return putVal(hash(key), key, value, true , true );
}
@Override
public boolean remove (Object key, Object value) {
return removeNode(hash(key), key, value, true , true ) != null ;
}
public boolean replace (K key, V oldValue, V newValue) {
Node<K,V> e; V v;
if ((e = getNode(hash(key), key)) != null &&
((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
e.value = newValue;
afterNodeAccess(e);
return true ;
}
return false ;
}
@Override
public V replace (K key, V value) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) != null ) {
V oldValue = e.value;
e.value = value;
afterNodeAccess(e);
return oldValue;
}
return null ;
}
………………
重要方法解析
1.putVal():
HashMap并没有直接提供putVal接口给用户使用,而是提供put()方法来进行使用(put方法的内部就是通过putVal来进行元素的插入)
step1:判断键值对数组table[i]是否为null,否则执行resize()进行扩容。
step2:根据key值计算hash值德大要插入的数组索引i,若table[i]==null,直接新建节点添加,转至step6,若table[i]不为空,转向step3.
step3:判断table[i]的首个元素是否和key一样,若相同直接进行覆盖,否则转至step4,这里的相同是指哈市Code和equals均相同。
step4:判断table[i]是否为treeNode,即table[i]是否为红黑树,若是红黑树直接在在树中插入键值对,否则转至step5。
step5:遍历table[i],判断链表长度是否大于8,大于8的话将链表转换为红黑树,在红黑树中执行插入操作,否则进行链表的插入操作,遍历过程中若发现key已经存在则直接进行覆盖。
step6:插入成功后,判断实际存在的键值对数量size是否超过了最大容量threshold,若超过,进行扩容。
final V putVal(int hash, K key, V value , boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0 )
n = (tab = resize()).length;
if ((p = tab[i = (n - 1 ) & hash]) == null )
tab[i] = newNode(hash, key, value , null );
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)、
e = ((TreeNode<K,V>)p).putTreeVal(this , tab, hash, key, value );
else {
for (int binCount = 0 ; ; ++binCount) {
if ((e = p.next) == null ) {
p.next = newNode(hash, key, value , null );
if (binCount >= TREEIFY_THRESHOLD - 1 )
treeifyBin(tab, hash);
break ;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break ;
p = e;
}
}
if (e != null ) {
V oldValue = e.value ;
if (!onlyIfAbsent || oldValue == null )
e.value = value ;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null ;
}
HashMap的数据存储实现原理:
(1)根据key值计算得到key.hash = (h=k.kashCode())^(h>>>16);
(2)根据key.hash计算得到桶数组的索引index = key.hash&(table.length-1),这样就找到了该key的存放位置了。
如果该位置没有数据,用该数据新生成一个节点保存新数据,返回null
如果该位置有数据是一个红黑树,那么执行相应的插入/更新操作
如果该位置有数据是一个链表,分两种情况:
一是链表中没有这个节点,采用尾插法插入该数据,返回null;
二是该链表上有这个节点(key.value是否相同),则找到该节点更新数据,返回旧数据。
(3)注意:HashMap的put会返回上一次保存的数据
2.getNode()方法
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1 ) & hash]) != null ) {
if (first.hash == hash &&
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null ) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null );
}
}
return null ;
}
3.resize()方法
(1)在JDK1.8中,resize方法是在hashMap中的键值对大于阈值或者初始化时,就调用resize方法进行扩容的
(2)每次扩容时,都是扩容两倍
(3)扩容后Node对象的位置要么在原位置,要么移动到原偏移量的二倍处。
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null ) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0 ;
if (oldCap > 0 ) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1 ) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1 ;
}
else if (oldThr > 0 )
newCap = oldThr;
else {
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int )(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0 ) {
float ft = (float )newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float )MAXIMUM_CAPACITY ?
(int )ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings ({"rawtypes" ,"unchecked" })
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null ) {
for (int j = 0 ; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null ) {
oldTab[j] = null ;
if (e.next == null )
newTab[e.hash & (newCap - 1 )] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this , newTab, j, oldCap);
else {
Node<K,V> loHead = null , loTail = null ;
Node<K,V> hiHead = null , hiTail = null ;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0 ) {
if (loTail == null )
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null )
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null );
if (loTail != null ) {
loTail.next = null ;
newTab[j] = loHead;
}
if (hiTail != null ) {
hiTail.next = null ;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
HashTable
HashTable采用数组+单链表来实现,HashTable实现了一个哈希表,它将键映射到值。任何非null对象可以用作键或者值。
用作键的对象必须实现hashCode方法和equals方法。HashTable的方法被synchronized修饰,因此是同步的、线程安全的。
HashTable和HashMap(JDK1.8之前)很像,唯一的区别就是HashTable中方法是线程安全的,也就是同步的。
构造函数
1.无参构造函数
public Hashtable () {
this (11 , 0.75 f);
}
2.指定初始化容量的构造函数
public Hashtable (int initialCapacity) {
this (initialCapacity, 0.75 f);
}
3.指定初始化容量和加载因子构造一个新的空哈希表
public Hashtable (int initialCapacity, float loadFactor) {
if (initialCapacity < 0 )
throw new IllegalArgumentException("Illegal Capacity: " +
initialCapacity);
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal Load: " +loadFactor);
if (initialCapacity==0 )
initialCapacity = 1 ;
this .loadFactor = loadFactor;
table = new Entry<?,?>[initialCapacity];
threshold = (int )Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1 );
}
HashTable和HashMap不同的是HashTable默认初始化容量为11,而HashMap默认初始化容量为10
部分源码剖析
public class Hashtable <K ,V >
extends Dictionary <K ,V >
implements Map <K ,V >, Cloneable , java .io .Serializable {
private transient Entry<?,?>[] table;
private transient int count ;
private int threshold;
private float loadFactor;
private transient int modCount = 0 ;
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());
}
public synchronized V put(K key, V value) {
if (value == null ) {
throw new NullPointerException();
}
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();
tab = table;
hash = key.hashCode();
index = (hash & 0x7FFFFFFF ) % tab.length;
}
@SuppressWarnings("unchecked" )
Entry<K,V> e = (Entry<K,V>) tab[index ];
tab[index ] = new Entry<>(hash, key, value, e);
count ++;
}
protected void rehash() {
int oldCapacity = table.length;
Entry<?,?>[] oldMap = table;
int newCapacity = (oldCapacity << 1 ) + 1 ;
if (newCapacity - MAX_ARRAY_SIZE > 0 ) {
if (oldCapacity == MAX_ARRAY_SIZE)
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;
}
}
}
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 ;
}
public synchronized V remove(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF ) % tab.length;
@SuppressWarnings("unchecked" )
Entry<K,V> e = (Entry<K,V>)tab[index ];
for (Entry<K,V> 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 ;
}
………………
}
HashMap和HashTable的区别
1.线程安全方面:HashMap是非线程安全的;HashTa是线程安全的,所以HashTable重量级一些,因为使用了synchronized关键字来保证线程安全。
2.key、value是否允许为空:HashMap允许key和value都为null(且key为null有且只能有一个);HashTable中key和value都不允许为null。
3.类结构:HashMap是JDK1.2引入的Map接口的一个实现;HashTable继承自JDK1.0的Dictionary虚拟类。
4.扩容方式:HashMap中默认数组大小为16,而且一定是2的倍数,每次扩容增加为原来的2倍;HashTable中数组的默认大小为11,扩容方式为old*2+1。
5.hash散列值的算法:HashMap是强制容量为2的幂,重新根据hashCode计算hash值,在使用hash和(hash表长度-1)进行与运算,也等于取模,
但是更加高效,取得的位置更加的分散,偶数技术保证了都会分散到;HashTable中hash值散列到hash表的算法是采用古老的除留余数法,
直接使用Object的hashCode来进行计算。
6.是否遵循Fail-Fast机制:HashMap遵循fail-fast机制;HashTable不遵循fail-fast机制。
@Test
public void test2() {
Hashtable< String ,String > table = new Hashtable< String ,String > ();
table. put("a" , "gao" );
table. put("b" , "zhu" );
table. put("c" , "zhang" );
table. put("d" , "sun" );
Iterator< String > keys = table. keySet(). iterator();
while (keys. hasNext()) {
String s = keys. next();
if ("c" . equals (s)) {
table. remove(s);
}else {
System. out. println(s);
}
}
}
@Test
public void test3() {
Map < String ,String > table2 = new HashMap< String ,String > ();
table2. put("a" , "gao" );
table2. put("b" , "zhu" );
table2. put("c" , "zhang" );
table2. put("d" , "sun" );
Iterator< String > keys = table2. keySet(). iterator();
while (keys. hasNext()) {
String s = keys. next();
if ("c" . equals (s)) {
table2. remove(s);
}else {
System. out. println(s);
}
}
}