JDK8-HashMap源码,2021最新大厂高频微服务面试总结

transient Set<Map.Entry<K,V>> entrySet;

/**

  • The number of key-value mappings contained in this map.

*/

transient int size;

/**

  • The number of times this HashMap has been structurally modified

  • Structural modifications are those that change the number of mappings in

  • the HashMap or otherwise modify its internal structure (e.g.,

  • rehash). This field is used to make iterators on Collection-views of

  • the HashMap fail-fast. (See ConcurrentModificationException).

*/

transient int modCount;

/**

  • The next size value at which to resize (capacity * load factor).

  • @serial

*/

// (The javadoc description is true upon serialization.

// Additionally, if the table array has not been allocated, this

// field holds the initial array capacity, or zero signifying

// DEFAULT_INITIAL_CAPACITY.)

int threshold;

/**

  • The load factor for the hash table.

  • @serial

*/

final float loadFactor;

/* ---------------- Public operations -------------- */

/**

  • Constructs an empty HashMap 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 HashMap 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 HashMap with the default initial capacity

  • (16) and the default load factor (0.75).

*/

public HashMap() {

this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted

}

/**

  • Constructs a new HashMap with the same mappings as the

  • specified Map. The HashMap is created with

  • default load factor (0.75) and an initial capacity sufficient to

  • hold the mappings

《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享

in the specified Map.

  • @param m the map whose mappings are to be placed in this map

  • @throws NullPointerException if the specified map is null

*/

public HashMap(Map<? extends K, ? extends V> m) {

this.loadFactor = DEFAULT_LOAD_FACTOR;

putMapEntries(m, false);

}

/**

  • Implements Map.putAll and Map constructor

  • @param m the map

  • @param evict false when initially constructing this map, else

  • true (relayed to method afterNodeInsertion).

*/

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {

int s = m.size();

if (s > 0) {

if (table == null) { // pre-size

float ft = ((float)s / loadFactor) + 1.0F;

int t = ((ft < (float)MAXIMUM_CAPACITY) ?

(int)ft : MAXIMUM_CAPACITY);

if (t > threshold)

threshold = tableSizeFor(t);

}

else if (s > threshold)

resize();

for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {

K key = e.getKey();

V value = e.getValue();

putVal(hash(key), key, value, false, evict);

}

}

}

/**

  • Returns the number of key-value mappings in this map.

  • @return the number of key-value mappings in this map

*/

public int size() {

return size;

}

/**

  • Returns true if this map contains no key-value mappings.

  • @return true if this map contains no key-value mappings

*/

public boolean isEmpty() {

return size == 0;

}

/**

  • Returns the value to which the specified key is mapped,

  • or {@code null} if this map contains no mapping for the key.

  • More formally, if this map contains a mapping from a key

  • {@code k} to a value {@code v} such that {@code (keynull ? knull :

  • key.equals(k))}, then this method returns {@code v}; otherwise

  • it returns {@code null}. (There can be at most one such mapping.)

  • A return value of {@code null} does not necessarily

  • 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;

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;

}

/**

  • Returns true if this map contains a mapping for the

  • specified key.

  • @param key The key whose presence in this map is to be tested

  • @return true if this map contains a mapping for the specified

  • key.

*/

public boolean containsKey(Object key) {

return getNode(hash(key), key) != null;

}

/**

  • 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 key, 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);

}

/**

  • 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;

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) // -1 for 1st

treeifyBin(tab, hash);

break;

}

if (e.hash == hash &&

((k = e.key) == key || (key != null && key.equals(k))))

break;

p = e;

}

}

if (e != null) { // existing mapping for key

V oldValue = e.value;

if (!onlyIfAbsent || oldValue == null)

e.value = value;

afterNodeAccess(e);

return oldValue;

}

}

++modCount;

if (++size > threshold)

resize();

afterNodeInsertion(evict);

return null;

}

/**

  • 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<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) {

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值