HashMap 是开发过程中,非常常用的一个类, 常常会被拿来与HashTable比较,什么什么鬼之类的。
HashMap与HashTable之间的区别:
1..HashMap允许Key Value 为null, HashTable 不可以
2..HashMap 非线程安全性, HashTable 是线程安全。 (HashTable 的方法有synchronized 同步锁, 而HashMap没有)
3..线程安全性就会影响速度的快慢, HashMap比HashTable快。
4..HashMap使用的是Iterator迭代器(fail-fast), 而HashTable 用的是enumerator. (iterator接口比enumerator多了一个remove,所以在多个线程对一个集合进行操作时,有可能会抛出ConcurrentModificationException异常【fail-fast】)
比较完之后,学习一下HashMap的源码
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { /** * * * **/ }
首先,HashMap继承了AbstractMap抽象类, 以及实现了Map,Cloneable,Serializable三个接口。
public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; }
看看HashMap中的get方法, 可以看到, 里面关键的方法就是getNode(hash(key),key)的方法
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) {
//hash & (length-1)得到对象的保存位 if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first;
//检查第一个是否符合,是则返回 if ((e = first.next) != null) { if (first instanceof TreeNode)
// 如果first 为TreeNode (红黑树)
//当链表长度超过8的时候将数组里面的链表转化成为红黑树return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
//与第一次检查条件一样,直至找到符合的e, 或者e.next==null跳出. return e; } while ((e = e.next) != null); } } return null; }
final TreeNode<K,V> getTreeNode(int h, Object k) { return ((parent != null) ? root() : this).find(h, k, null); }