为了应付面试,所以就着HashMap看一下源码,网上的面试题,五花八门的太多了,感觉不太对劲,还是自己看看吧。
构造方法
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
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);
}
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
//只是给负载容量赋值
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
构造方法其实就是给负载因子loadFactor以及扩容时元素个数threshold赋值,真正创建Node数据的操作,源自于put方法中的resize()方法。
Put方法
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
put方法,底层调了个putVal方法,第四个参数代表如果在hashMap中存在key相同的情况下,是否替换value,false代表替换,第五个参数在hashMap的put方法中用到的方法是个空方法体,先不用考虑。
/**
* Implements Map.put and related methods.
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//是否只是新创建的的hashMap
if ((tab = table) == null || (n = tab.length) == 0)
//是新创建的hashMap,利用resize方法来创建新的Node数组
n = (tab = resize()).length;
//判断当前新插入的node节点所在的数组下标位置是否存在元素
if ((p = tab[i = (n - 1) & hash]) == null)
//不存在,直接创建一个新node节点插入到下标位置
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//数组下标存在node节点的情况下,需要通过拉链法在node节点上添加元素了
//当前链表头节点的key等于put进来的key
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//将头节点元素赋值给e变量
e = p;
else if (p instanceof TreeNode)
//头节点如果是树的话,采用树化手段来进行插入了
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//通过for循环,来遍历头节点p名下的链表
for (int binCount = 0; ; ++binCount) {
//到达尾节点,没有找到相同的元素
if ((e = p.next) == null) {
//创建新的节点
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//链表长度大于等于8,扩容或者树化
treeifyBin(tab, hash);
break;
}
//在循环中,发现存在与key相同的节点,此时链表上的节点赋值给e变量
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//e变量指向对象不为空,代表存在key值相同的链表元素
if (e != null) { // existing mapping for key
V oldValue = e.value;
//将新值赋值给老值
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
//返回老值
return oldValue;
}
}
//记录总共put了多少次,一个记录字段
++modCount;
//接下来的过程,是新插入节点的流程
if (++size > threshold)
//扩容的步骤,在最后做了,如果插入的元素数量大于容量*负载因子,扩容
resize();
//hashMap中是个空方法,先不用管
afterNodeInsertion(evict);
return null;
}
能捋清,但是不太好记住。
resize方法
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
final Node<K,V>[] resize() {
//将node原有数组的引用放到当前数组上
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; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
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)
//老数组j下标下只有一个元素
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
//TreeNode,按照树节点的方式来进行插入
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
//划分成了两个链表
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
//如果二次hash老数组下标为0的话,生成一个loHead链表
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
//和老链表取模之后,不为0的数据,存放到另一个链表
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
//取模为0的数据,存放到Node老数组原先的下标位置
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
//取模不为0的数据,存放到新的位置
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
reisze()方法的目的就是为了扩容,不过在扩容方面做了优化,在往新node数组添加元素时,会将二次hash取模后值为0的数据存放到原有的位置中。
get方法
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>
* indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}.
* The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*
* @see #put(Object, Object)
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* Implements Map.get and related methods.
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//通过二次hash得到tab数组上某个下标的第一个链表元素
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//判断值是否相等
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)
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;
}
get方法其实底层就是调用了一个getNode()方法,在getNode方法中,通过二次hash获取到下标位置,判断当前元素是否与put进来的value相等。不相等,在根据节点的状态是链表状态还是数组状态,决定流程。
containsKey方法
底层也是getNode方法,不做过多描述。
树化的方法先不统计了,后面需要学的东西有点多,如果面试有问到的,再接着看。