JDK8-HashMap源码,2024年最新java银行项目面试

先自我介绍一下,小编浙江大学毕业,去过华为、字节跳动等大厂,目前阿里P7

深知大多数程序员,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

如果你需要这些资料,可以添加V获取:vip1024b (备注Java)
img

正文

public final int hashCode() {

return Objects.hashCode(key) ^ Objects.hashCode(value); //key和value - Objects.hashCode - 亦或求值

}

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;

}

}

/* ---------------- Static utilities -------------- */

/**

  • Computes key.hashCode() and spreads (XORs) higher bits of hash

  • to lower. Because the table uses power-of-two masking, sets of

  • hashes that vary only in bits above the current mask will

  • always collide【碰撞】. (Among known examples are sets of Float keys

  • holding consecutive【连续的】 whole numbers in small tables.) So we

  • apply a transform that spreads the impact of higher bits

  • downward. There is a tradeoff between speed, utility, and

  • quality of bit-spreading. Because many common sets of hashes

  • are already reasonably distributed (so don’t benefit from

  • spreading), and because we use trees to handle large sets of

  • collisions in bins, we just XOR some shifted bits in the

  • cheapest possible way to reduce systematic lossage, as well as

  • to incorporate impact of the highest bits that would otherwise

  • never be used in index calculations because of table bounds.

*/

static final int hash(Object key) {

int h;

return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); //重新计算hashing值,无符号右移16位然后再亦或运算

}

/**

  • Returns x’s Class if it is of the form "class C implements

  • Comparable", else null.

*/

static Class<?> comparableClassFor(Object x) {

if (x instanceof Comparable) {

Class<?> c; Type[] ts, as; Type t; ParameterizedType p;

if ((c = x.getClass()) == String.class) // bypass checks

return c;

if ((ts = c.getGenericInterfaces()) != null) {

for (int i = 0; i < ts.length; ++i) {

if (((t = ts[i]) instanceof ParameterizedType) &&

((p = (ParameterizedType)t).getRawType() ==

Comparable.class) &&

(as = p.getActualTypeArguments()) != null &&

as.length == 1 && as[0] == c) // type arg is c

return c;

}

}

}

return null;

}

/**

  • Returns k.compareTo(x) if x matches kc (k’s screened comparable

  • class), else 0.

*/

@SuppressWarnings({“rawtypes”,“unchecked”}) // for cast to Comparable

static int compareComparables(Class<?> kc, Object k, Object x) {

return (x == null || x.getClass() != kc ? 0 :

((Comparable)k).compareTo(x));

}

/**

  • Returns a power of two size for the given target capacity.

*/

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;

}

/* ---------------- Fields -------------- */

/**

  • The table, initialized on first use, and resized as

  • necessary. When allocated, length is always a power of two.

  • (We also tolerate length zero in some operations to allow

  • bootstrapping mechanics that are currently not needed.)

*/

transient Node<K,V>[] table;

/**

  • Holds cached entrySet(). Note that AbstractMap fields are used

  • for keySet() and values().

*/

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

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 { // preserve order

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;

}

/**

  • Replaces all linked nodes in bin at index for given hash unless

  • table is too small, in which case resizes instead.

*/

final void treeifyBin(Node<K,V>[] tab, int hash) {

int n, index; Node<K,V> e;

if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)

resize();

else if ((e = tab[index = (n - 1) & hash]) != null) {

TreeNode<K,V> hd = null, tl = null;

do {

TreeNode<K,V> p = replacementTreeNode(e, null);

if (tl == null)

hd = p;

else {

p.prev = tl;

tl.next = p;

}

tl = p;

} while ((e = e.next) != null);

if ((tab[index] = hd) != null)

hd.treeify(tab);

}

}

/**

  • Copies all of the mappings from the specified map to this map.

  • These mappings will replace any mappings that this map had for

  • any of the keys currently in the specified map.

  • @param m mappings to be stored in this map

  • @throws NullPointerException if the specified map is null

*/

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

putMapEntries(m, true);

}

/**

  • Removes the mapping for the specified key from this map if present.

  • @param key key whose mapping is to be removed from the map

  • @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 remove(Object key) {

Node<K,V> e;

return (e = removeNode(hash(key), key, null, false, true)) == null ?

null : e.value;

}

/**

  • Implements Map.remove and related methods

  • @param hash hash for key

  • @param key the key

  • @param value the value to match if matchValue, else ignored

  • @param matchValue if true only remove if value is equal

  • @param movable if false do not move other nodes while removing

  • @return the node, or null if none

*/

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;

}

/**

  • Removes all of the mappings from this map.

  • The map will be empty after this call returns.

*/

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;

}

}

/**

  • Returns true if this map maps one or more keys to the

  • specified value.

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

  • @return true if this map maps one or more keys to the

  •     specified value
    

*/

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;

}

/**

  • Returns a {@link Set} view of the keys contained in this map.

  • The set is backed by the map, so changes to the map are

  • reflected in the set, and vice-versa. If the map is modified

  • while an iteration over the set is in progress (except through

  • the iterator’s own remove operation), the results of

  • the iteration are undefined. The set supports element removal,

  • which removes the corresponding mapping from the map, via the

  • Iterator.remove, Set.remove,

  • removeAll, retainAll, and clear

  • operations. It does not support the add or addAll

  • operations.

  • @return a set view of the keys contained in this map

*/

public Set keySet() {

Set ks = keySet;

if (ks == null) {

ks = new KeySet();

keySet = ks;

}

return ks;

}

final class KeySet extends AbstractSet {

public final int size() { return size; }

public final void clear() { HashMap.this.clear(); }

public final Iterator 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 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();

}

}

}

/**

  • Returns a {@link Collection} view of the values contained in this map.

  • The collection is backed by the map, so changes to the map are

  • reflected in the collection, and vice-versa. If the map is

  • modified while an iteration over the collection is in progress

  • (except through the iterator’s own remove operation),

  • the results of the iteration are undefined. The collection

  • supports element removal, which removes the corresponding

  • mapping from the map, via the Iterator.remove,

  • Collection.remove, removeAll,

  • retainAll and clear operations. It does not

  • support the add or addAll operations.

  • @return a view of the values contained in this map

*/

public Collection values() {

Collection vs = values;

if (vs == null) {

vs = new Values();

values = vs;

}

return vs;

}

final class Values extends AbstractCollection {

public final int size() { return size; }

public final void clear() { HashMap.this.clear(); }

public final Iterator iterator() { return new ValueIterator(); }

public final boolean contains(Object o) { return containsValue(o); }

public final Spliterator spliterator() {

return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);

}

public final void forEach(Consumer<? super 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.value);

}

if (modCount != mc)

throw new ConcurrentModificationException();

}

}

}

/**

  • Returns a {@link Set} view of the mappings contained in this map.

  • The set is backed by the map, so changes to the map are

  • reflected in the set, and vice-versa. If the map is modified

  • while an iteration over the set is in progress (except through

  • the iterator’s own remove operation, or through the

  • setValue operation on a map entry returned by the

  • iterator) the results of the iteration are undefined. The set

  • supports element removal, which removes the corresponding

  • mapping from the map, via the Iterator.remove,

  • Set.remove, removeAll, retainAll and

  • clear operations. It does not support the

  • add or addAll operations.

  • @return a set view of the mappings contained in this map

*/

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();

}

}

}

// Overrides of JDK8 Map extension methods

@Override

public V getOrDefault(Object key, V defaultValue) {

Node<K,V> e;

return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;

}

@Override

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;

}

@Override

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;

}

@Override

public V computeIfAbsent(K key,

Function<? super K, ? extends V> mappingFunction) {

if (mappingFunction == null)

throw new NullPointerException();

int hash = hash(key);

Node<K,V>[] tab; Node<K,V> first; int n, i;

int binCount = 0;

TreeNode<K,V> t = null;

Node<K,V> old = null;

if (size > threshold || (tab = table) == null ||

(n = tab.length) == 0)

n = (tab = resize()).length;

if ((first = tab[i = (n - 1) & hash]) != null) {

if (first instanceof TreeNode)

old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);

else {

Node<K,V> e = first; K k;

do {

if (e.hash == hash &&

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

old = e;

break;

}

++binCount;

} while ((e = e.next) != null);

}

V oldValue;

if (old != null && (oldValue = old.value) != null) {

afterNodeAccess(old);

return oldValue;

}

}

V v = mappingFunction.apply(key);

if (v == null) {

return null;

} else if (old != null) {

old.value = v;

afterNodeAccess(old);

return v;

}

else if (t != null)

t.putTreeVal(this, tab, hash, key, v);

else {

tab[i] = newNode(hash, key, v, first);

if (binCount >= TREEIFY_THRESHOLD - 1)

treeifyBin(tab, hash);

}

++modCount;

++size;

afterNodeInsertion(true);

return v;

}

public V computeIfPresent(K key,

BiFunction<? super K, ? super V, ? extends V> remappingFunction) {

if (remappingFunction == null)

throw new NullPointerException();

Node<K,V> e; V oldValue;

int hash = hash(key);

if ((e = getNode(hash, key)) != null &&

(oldValue = e.value) != null) {

V v = remappingFunction.apply(key, oldValue);

if (v != null) {

e.value = v;

afterNodeAccess(e);

return v;

}

else

removeNode(hash, key, null, false, true);

}

return null;

}

@Override

public V compute(K key,

BiFunction<? super K, ? super V, ? extends V> remappingFunction) {

if (remappingFunction == null)

throw new NullPointerException();

int hash = hash(key);

Node<K,V>[] tab; Node<K,V> first; int n, i;

int binCount = 0;

TreeNode<K,V> t = null;

Node<K,V> old = null;

if (size > threshold || (tab = table) == null ||

(n = tab.length) == 0)

n = (tab = resize()).length;

if ((first = tab[i = (n - 1) & hash]) != null) {

if (first instanceof TreeNode)

old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);

else {

Node<K,V> e = first; K k;

do {

if (e.hash == hash &&

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

old = e;

break;

}

++binCount;

} while ((e = e.next) != null);

}

}

V oldValue = (old == null) ? null : old.value;

V v = remappingFunction.apply(key, oldValue);

if (old != null) {

if (v != null) {

old.value = v;

afterNodeAccess(old);

}

else

removeNode(hash, key, null, false, true);

}

else if (v != null) {

if (t != null)

t.putTreeVal(this, tab, hash, key, v);

else {

tab[i] = newNode(hash, key, v, first);

if (binCount >= TREEIFY_THRESHOLD - 1)

treeifyBin(tab, hash);

}

++modCount;

++size;

afterNodeInsertion(true);

}

return v;

}

@Override

public V merge(K key, V value,

BiFunction<? super V, ? super V, ? extends V> remappingFunction) {

if (value == null)

throw new NullPointerException();

if (remappingFunction == null)

throw new NullPointerException();

int hash = hash(key);

Node<K,V>[] tab; Node<K,V> first; int n, i;

int binCount = 0;

TreeNode<K,V> t = null;

Node<K,V> old = null;

if (size > threshold || (tab = table) == null ||

(n = tab.length) == 0)

n = (tab = resize()).length;

if ((first = tab[i = (n - 1) & hash]) != null) {

if (first instanceof TreeNode)

old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);

else {

Node<K,V> e = first; K k;

do {

if (e.hash == hash &&

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

old = e;

break;

}

++binCount;

} while ((e = e.next) != null);

}

}

if (old != null) {

V v;

if (old.value != null)

v = remappingFunction.apply(old.value, value);

else

v = value;

if (v != null) {

old.value = v;

afterNodeAccess(old);

}

else

removeNode(hash, key, null, false, true);

return v;

}

if (value != null) {

if (t != null)

t.putTreeVal(this, tab, hash, key, value);

else {

tab[i] = newNode(hash, key, value, first);

if (binCount >= TREEIFY_THRESHOLD - 1)

treeifyBin(tab, hash);

}

++modCount;

++size;

afterNodeInsertion(true);

}

return value;

}

@Override

public void forEach(BiConsumer<? super K, ? super 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.key, e.value);

}

if (modCount != mc)

throw new ConcurrentModificationException();

}

}

@Override

public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {

Node<K,V>[] tab;

if (function == 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) {

e.value = function.apply(e.key, e.value);

}

}

if (modCount != mc)

throw new ConcurrentModificationException();

}

}

/* ------------------------------------------------------------ */

// Cloning and serialization

/**

  • Returns a shallow copy of this HashMap instance: the keys and

  • values themselves are not cloned.

  • @return a shallow copy of this map

*/

@SuppressWarnings(“unchecked”)

@Override

public Object clone() {

HashMap<K,V> result;

try {

result = (HashMap<K,V>)super.clone();

} catch (CloneNotSupportedException e) {

// this shouldn’t happen, since we are Cloneable

throw new InternalError(e);

}

result.reinitialize();

result.putMapEntries(this, false);

return result;

}

// These methods are also used when serializing HashSets

final float loadFactor() { return loadFactor; }

final int capacity() {

return (table != null) ? table.length :

(threshold > 0) ? threshold :

DEFAULT_INITIAL_CAPACITY;

}

/**

  • Save the state of the HashMap instance to a stream (i.e.,

  • serialize it).

  • @serialData The capacity of the HashMap (the length of the

  •         bucket array) is emitted (int), followed by the
    
  •         <i>size</i> (an int, the number of key-value
    
  •         mappings), followed by the key (Object) and value (Object)
    
  •         for each key-value mapping.  The key-value mappings are
    
  •         emitted in no particular order.
    

*/

private void writeObject(java.io.ObjectOutputStream s)

throws IOException {

int buckets = capacity();

// Write out the threshold, loadfactor, and any hidden stuff

s.defaultWriteObject();

s.writeInt(buckets);

s.writeInt(size);

internalWriteEntries(s);

}

/**

  • Reconstitute the {@code HashMap} instance from a stream (i.e.,

  • deserialize it).

*/

private void readObject(java.io.ObjectInputStream s)

throws IOException, ClassNotFoundException {

// Read in the threshold (ignored), loadfactor, and any hidden stuff

s.defaultReadObject();

reinitialize();

if (loadFactor <= 0 || Float.isNaN(loadFactor))

throw new InvalidObjectException("Illegal load factor: " +

loadFactor);

s.readInt(); // Read and ignore number of buckets

int mappings = s.readInt(); // Read number of mappings (size)

if (mappings < 0)

throw new InvalidObjectException("Illegal mappings count: " +

mappings);

else if (mappings > 0) { // (if zero, use defaults)

// Size the table using given load factor only if within

// range of 0.25…4.0

float lf = Math.min(Math.max(0.25f, loadFactor), 4.0f);

float fc = (float)mappings / lf + 1.0f;

int cap = ((fc < DEFAULT_INITIAL_CAPACITY) ?

DEFAULT_INITIAL_CAPACITY :

(fc >= MAXIMUM_CAPACITY) ?

MAXIMUM_CAPACITY :

tableSizeFor((int)fc));

float ft = (float)cap * lf;

threshold = ((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY) ?

(int)ft : Integer.MAX_VALUE);

// Check Map.Entry[].class since it’s the nearest public type to

// what we’re actually creating.

SharedSecrets.getJavaOISAccess().checkArray(s, Map.Entry[].class, cap);

@SuppressWarnings({“rawtypes”,“unchecked”})

Node<K,V>[] tab = (Node<K,V>[])new Node[cap];

table = tab;

// Read the keys and values, and put the mappings in the HashMap

for (int i = 0; i < mappings; i++) {

@SuppressWarnings(“unchecked”)

K key = (K) s.readObject();

@SuppressWarnings(“unchecked”)

V value = (V) s.readObject();

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

}

}

}

/* ------------------------------------------------------------ */

// iterators

abstract class HashIterator {

Node<K,V> next; // next entry to return

Node<K,V> current; // current entry

int expectedModCount; // for fast-fail

int index; // current slot

HashIterator() {

expectedModCount = modCount;

Node<K,V>[] t = table;

current = next = null;

index = 0;

if (t != null && size > 0) { // advance to first entry

do {} while (index < t.length && (next = t[index++]) == null);

}

}

public final boolean hasNext() {

return next != null;

}

final Node<K,V> nextNode() {

Node<K,V>[] t;

Node<K,V> e = next;

if (modCount != expectedModCount)

throw new ConcurrentModificationException();

if (e == null)

throw new NoSuchElementException();

if ((next = (current = e).next) == null && (t = table) != null) {

do {} while (index < t.length && (next = t[index++]) == null);

}

return e;

}

public final void remove() {

Node<K,V> p = current;

if (p == null)

throw new IllegalStateException();

if (modCount != expectedModCount)

throw new ConcurrentModificationException();

current = null;

K key = p.key;

removeNode(hash(key), key, null, false, false);

expectedModCount = modCount;

}

}

final class KeyIterator extends HashIterator

implements Iterator {

public final K next() { return nextNode().key; }

}

final class ValueIterator extends HashIterator

implements Iterator {

public final V next() { return nextNode().value; }

}

final class EntryIterator extends HashIterator

implements Iterator<Map.Entry<K,V>> {

public final Map.Entry<K,V> next() { return nextNode(); }

}

/* ------------------------------------------------------------ */

// spliterators

static class HashMapSpliterator<K,V> {

final HashMap<K,V> map;

Node<K,V> current; // current node

int index; // current index, modified on advance/split

int fence; // one past last index

int est; // size estimate

int expectedModCount; // for comodification checks

HashMapSpliterator(HashMap<K,V> m, int origin,

int fence, int est,

int expectedModCount) {

this.map = m;

this.index = origin;

this.fence = fence;

this.est = est;

this.expectedModCount = expectedModCount;

}

final int getFence() { // initialize fence and size on first use

int hi;

if ((hi = fence) < 0) {

HashMap<K,V> m = map;

est = m.size;

expectedModCount = m.modCount;

Node<K,V>[] tab = m.table;

hi = fence = (tab == null) ? 0 : tab.length;

}

return hi;

}

public final long estimateSize() {

getFence(); // force init

return (long) est;

}

}

static final class KeySpliterator<K,V>

extends HashMapSpliterator<K,V>

implements Spliterator {

KeySpliterator(HashMap<K,V> m, int origin, int fence, int est,

int expectedModCount) {

super(m, origin, fence, est, expectedModCount);

}

public KeySpliterator<K,V> trySplit() {

int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;

return (lo >= mid || current != null) ? null :

new KeySpliterator<>(map, lo, index = mid, est >>>= 1,

expectedModCount);

}

public void forEachRemaining(Consumer<? super K> action) {

int i, hi, mc;

if (action == null)

throw new NullPointerException();

HashMap<K,V> m = map;

Node<K,V>[] tab = m.table;

if ((hi = fence) < 0) {

mc = expectedModCount = m.modCount;

hi = fence = (tab == null) ? 0 : tab.length;

}

else

mc = expectedModCount;

if (tab != null && tab.length >= hi &&

(i = index) >= 0 && (i < (index = hi) || current != null)) {

Node<K,V> p = current;

current = null;

do {

if (p == null)

p = tab[i++];

else {

action.accept(p.key);

p = p.next;

}

} while (p != null || i < hi);

if (m.modCount != mc)

throw new ConcurrentModificationException();

}

}

public boolean tryAdvance(Consumer<? super K> action) {

int hi;

if (action == null)

throw new NullPointerException();

Node<K,V>[] tab = map.table;

if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {

while (current != null || index < hi) {

if (current == null)

current = tab[index++];

else {

K k = current.key;

current = current.next;

action.accept(k);

if (map.modCount != expectedModCount)

throw new ConcurrentModificationException();

return true;

}

}

}

return false;

}

public int characteristics() {

return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |

Spliterator.DISTINCT;

}

}

static final class ValueSpliterator<K,V>

extends HashMapSpliterator<K,V>

implements Spliterator {

ValueSpliterator(HashMap<K,V> m, int origin, int fence, int est,

int expectedModCount) {

super(m, origin, fence, est, expectedModCount);

}

public ValueSpliterator<K,V> trySplit() {

int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;

return (lo >= mid || current != null) ? null :

new ValueSpliterator<>(map, lo, index = mid, est >>>= 1,

expectedModCount);

}

public void forEachRemaining(Consumer<? super V> action) {

int i, hi, mc;

if (action == null)

throw new NullPointerException();

HashMap<K,V> m = map;

Node<K,V>[] tab = m.table;

if ((hi = fence) < 0) {

mc = expectedModCount = m.modCount;

hi = fence = (tab == null) ? 0 : tab.length;

}

else

mc = expectedModCount;

if (tab != null && tab.length >= hi &&

(i = index) >= 0 && (i < (index = hi) || current != null)) {

Node<K,V> p = current;

current = null;

do {

if (p == null)

p = tab[i++];

else {

action.accept(p.value);

p = p.next;

}

} while (p != null || i < hi);

if (m.modCount != mc)

throw new ConcurrentModificationException();

}

}

public boolean tryAdvance(Consumer<? super V> action) {

int hi;

if (action == null)

throw new NullPointerException();

Node<K,V>[] tab = map.table;

if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {

while (current != null || index < hi) {

if (current == null)

current = tab[index++];

else {

V v = current.value;

current = current.next;

action.accept(v);

if (map.modCount != expectedModCount)

throw new ConcurrentModificationException();

return true;

}

}

}

return false;

}

public int characteristics() {

return (fence < 0 || est == map.size ? Spliterator.SIZED : 0);

}

}

static final class EntrySpliterator<K,V>

extends HashMapSpliterator<K,V>

implements Spliterator<Map.Entry<K,V>> {

EntrySpliterator(HashMap<K,V> m, int origin, int fence, int est,

int expectedModCount) {

super(m, origin, fence, est, expectedModCount);

}

public EntrySpliterator<K,V> trySplit() {

int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;

return (lo >= mid || current != null) ? null :

new EntrySpliterator<>(map, lo, index = mid, est >>>= 1,

expectedModCount);

}

public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {

int i, hi, mc;

if (action == null)

throw new NullPointerException();

HashMap<K,V> m = map;

Node<K,V>[] tab = m.table;

if ((hi = fence) < 0) {

mc = expectedModCount = m.modCount;

hi = fence = (tab == null) ? 0 : tab.length;

}

else

mc = expectedModCount;

if (tab != null && tab.length >= hi &&

(i = index) >= 0 && (i < (index = hi) || current != null)) {

Node<K,V> p = current;

current = null;

do {

if (p == null)

p = tab[i++];

else {

action.accept§;

p = p.next;

}

} while (p != null || i < hi);

if (m.modCount != mc)

throw new ConcurrentModificationException();

}

}

public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {

int hi;

if (action == null)

throw new NullPointerException();

Node<K,V>[] tab = map.table;

if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {

while (current != null || index < hi) {

if (current == null)

current = tab[index++];

else {

Node<K,V> e = current;

current = current.next;

action.accept(e);

if (map.modCount != expectedModCount)

throw new ConcurrentModificationException();

return true;

}

}

}

return false;

}

public int characteristics() {

return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |

Spliterator.DISTINCT;

}

}

最后

为什么我不完全主张自学?
平台上的大牛基本上都有很多年的工作经验了,你有没有想过之前行业的门槛是什么样的,现在行业门槛是什么样的?以前企业对于程序员能力要求没有这么高,甚至十多年前你只要会写个“Hello World”,你都可以入门这个行业,所以以前要入门是完全可以入门的。
②现在也有一些优秀的年轻大牛,他们或许也是自学成才,但是他们一定是具备优秀的学习能力,优秀的自我管理能力(时间管理,静心坚持等方面)以及善于发现问题并总结问题。
如果说你认为你的目标十分明确,能做到第②点所说的几个点,以目前的市场来看,你才真正的适合去自学。

除此之外,对于绝大部分人来说,报班一定是最好的一种快速成长的方式。但是有个问题,现在市场上的培训机构质量参差不齐,如果你没有找准一个好的培训班,完全是浪费精力,时间以及金钱,这个需要自己去甄别选择。

我个人建议线上比线下的性价比更高,线下培训价格基本上没2W是下不来的,线上教育现在比较成熟了,此次疫情期间,学生基本上都感受过线上的学习模式。相比线下而言,线上的优势以我的了解主要是以下几个方面:
①价格:线上的价格基本上是线下的一半;
②老师:相对而言线上教育的师资力量比线下更强大也更加丰富,资源更好协调;
③时间:学习时间相对而言更自由,不用裸辞学习,适合边学边工作,降低生活压力;
④课程:从课程内容来说,确实要比线下讲的更加深入。

应该学哪些技术才能达到企业的要求?(下图总结)

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip1024b (备注Java)
img

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

K,V>

extends HashMapSpliterator<K,V>

implements Spliterator<Map.Entry<K,V>> {

EntrySpliterator(HashMap<K,V> m, int origin, int fence, int est,

int expectedModCount) {

super(m, origin, fence, est, expectedModCount);

}

public EntrySpliterator<K,V> trySplit() {

int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;

return (lo >= mid || current != null) ? null :

new EntrySpliterator<>(map, lo, index = mid, est >>>= 1,

expectedModCount);

}

public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {

int i, hi, mc;

if (action == null)

throw new NullPointerException();

HashMap<K,V> m = map;

Node<K,V>[] tab = m.table;

if ((hi = fence) < 0) {

mc = expectedModCount = m.modCount;

hi = fence = (tab == null) ? 0 : tab.length;

}

else

mc = expectedModCount;

if (tab != null && tab.length >= hi &&

(i = index) >= 0 && (i < (index = hi) || current != null)) {

Node<K,V> p = current;

current = null;

do {

if (p == null)

p = tab[i++];

else {

action.accept§;

p = p.next;

}

} while (p != null || i < hi);

if (m.modCount != mc)

throw new ConcurrentModificationException();

}

}

public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {

int hi;

if (action == null)

throw new NullPointerException();

Node<K,V>[] tab = map.table;

if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {

while (current != null || index < hi) {

if (current == null)

current = tab[index++];

else {

Node<K,V> e = current;

current = current.next;

action.accept(e);

if (map.modCount != expectedModCount)

throw new ConcurrentModificationException();

return true;

}

}

}

return false;

}

public int characteristics() {

return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |

Spliterator.DISTINCT;

}

}

最后

为什么我不完全主张自学?
平台上的大牛基本上都有很多年的工作经验了,你有没有想过之前行业的门槛是什么样的,现在行业门槛是什么样的?以前企业对于程序员能力要求没有这么高,甚至十多年前你只要会写个“Hello World”,你都可以入门这个行业,所以以前要入门是完全可以入门的。
②现在也有一些优秀的年轻大牛,他们或许也是自学成才,但是他们一定是具备优秀的学习能力,优秀的自我管理能力(时间管理,静心坚持等方面)以及善于发现问题并总结问题。
如果说你认为你的目标十分明确,能做到第②点所说的几个点,以目前的市场来看,你才真正的适合去自学。

除此之外,对于绝大部分人来说,报班一定是最好的一种快速成长的方式。但是有个问题,现在市场上的培训机构质量参差不齐,如果你没有找准一个好的培训班,完全是浪费精力,时间以及金钱,这个需要自己去甄别选择。

我个人建议线上比线下的性价比更高,线下培训价格基本上没2W是下不来的,线上教育现在比较成熟了,此次疫情期间,学生基本上都感受过线上的学习模式。相比线下而言,线上的优势以我的了解主要是以下几个方面:
①价格:线上的价格基本上是线下的一半;
②老师:相对而言线上教育的师资力量比线下更强大也更加丰富,资源更好协调;
③时间:学习时间相对而言更自由,不用裸辞学习,适合边学边工作,降低生活压力;
④课程:从课程内容来说,确实要比线下讲的更加深入。

应该学哪些技术才能达到企业的要求?(下图总结)

[外链图片转存中…(img-ZnvBePPv-1713634989370)]

[外链图片转存中…(img-DJI4oOvz-1713634989371)]

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip1024b (备注Java)
[外链图片转存中…(img-PyWGcywS-1713634989372)]

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值