1. 分析hashMap.containsKey
hashMap.containsKey(value)
的时间复杂度为什么是O(1)呢?这个就要来看一下源码了
/**
* Returns <tt>true</tt> if this map contains a mapping for the
* specified key.
*
* @param key The key whose presence in this map is to be tested
* @return <tt>true</tt> if this map contains a mapping for the specified
* key.
*/
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
调用了getNode(hash(key), key)
方法,参数分别为key的hash值,key。再来看下这个方法的实现
/**
* 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