Too hard core! This HashMap source code analysis can definitely be called the Bible. You can quickly master rabbitmq in 60 minutes

mb61ab40ce80d9c 2022-01-15 03:26:42 阅读数:863

hard core hashmap source code

public static void main(String[] args) {
HashMap<String, Object> map = new HashMap<>();
map.put(null,null);
System.out.println(map);//{null=null}
}

If so, there is no wrong report ; Add one null Of key and value have a look ; No more code , The final output is still a {null=null}; explain HashMap Of key Is the only one. ;? How to guarantee key The only thing I'll continue to analyze later ;

  • Keep reading the official instructions ,HashMap And HashTable Here's the difference ,HashMap Out of sync ,HashTable Don't allow key,value by null; Practice a

public static void main(String[] args) {
Hashtable hashtable = new Hashtable();
hashtable.put(null,null);
}

The console is red !!! The output is as follows , shock ,HashTable Of key,value I really can't do it for null;

{null=null}Exception in thread "main"
java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:459)
at test.HashMapTest.main(HashMapTest.java:17)

Process finished with exit code 1

Click the source code to see ,HashTable Of put Method extra large Make Make sure at the beginning that key,value Not for null,synchronized modification ; Life is questionable , Because knowledge seekers have never used Hashtable Playing with code ;

public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}

// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;

  • Keep reading the official instructions ,HashMap No guarantee Map The order of contents in ; Do it again , If so , In the end, what should be allowed map The order is different ? Follow up analysis

public static void main(String[] args) {
HashMap<String, Object> map = new HashMap<>();
map.put(" Early in the morning "," The baby cried ");
map.put(" At noon, "," The baby is hungry ");
map.put(" evening "," Baby doesn't want to go to sleep ");
System.out.println(map);//{ At noon, = The baby is hungry , evening = Baby doesn't want to go to sleep , Early in the morning = The baby cried }
}

The follow-up official explanation can not be described in a few words , The appetizer is over , Let's take a look at the specific source code , When reviewing, remember to look at the tips Tip;

Tip:

HashMap allow key and value All for null;key Have uniqueness ;

HashMap And HashTable Here's the difference ,HashMap Out of sync ,HashTable Don't allow key,value by null;

HashMap No guarantee Map The order of contents in

2.2 Analysis of space parameter construction method

Test code

public static void main(String[] args) {
HashMap<String, Objec

《 A big factory Java Analysis of interview questions + Back end development learning notes + The latest architecture explanation video + Practical project source code handout 》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 Full content open source sharing

t> map = new HashMap<>();
}

The source code of the construction method is as follows , issue HashMap Load factor of loadFactor The value of is the default value 0.75;

public HashMap() {// Default factor DEFAULT_LOAD_FACTOR=0.75; The initialization capacity is 16
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

I went through the steps as follows

HashMap --> AbstractMap --> Object

look down HashMap The father map of , The structure is very simple, right ;

image.png

See this way , Knowledge seekers have 2 A question

Question 1 : Load factor 0.75 What is it? ?

Question two : Initialize capacity 16 Where is the ?

Let's start with the initialization capacity 16 problem , Knowledge seekers find member variables , The default initialization capacity field value is 16; And the default initialization value must be 2 Multiple ;

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 Default initialization capacity

Answer load factor 0.75 Refer to HashMap An expansion mechanism of ; such as The expansion factor is 0.7, Suppose the capacity is 10; When the inserted data reaches the 100.7 = 7 It will expand capacity ; Then the knowledge seeker calculates HashMap The expansion algorithm of ,0.75 16 = 12; So that's insertion 12 After the count HashMap There will be expansion ;

Tip: HashMap Default factor 0.75; Initialize capacity 16; If the given initialization capacity is 12, Insert 12 If you insert data after the number, the capacity will be expanded ;

2.3 HashMap Implementation principle analysis

The official source code is as follows :HashMap The implementation of is implemented by bucket and hash table , When the capacity of the bucket is too large, it will turn into a tree node ( And TreeMap similar , because TreeMap The bottom layer is the red black tree , So it's also right to say that the barrel turns into a red and black tree );

Throw a question about what a barrel is ?

Let's know what a hash table is before we answer the bucket (HashTable)

Hash table is essentially an array of linked lists ; after Hash The result of the algorithm int Value to find the corresponding position on the array ; Lose a picture to the readers ;

image.png

Knowledge seekers really break their hearts for readers , Throw another calculation hash The way of value is for you ; Remember to review java Basics String Class hashCode() Method ; if 2 The objects are the same ,hash Same value ; if 2 The contents of strings are the same (equals Method ),hash Same value ;

public static void main(String[] args) {
int hash_morning = Objects.hashCode(" Early in the morning ");
int hash_night = Objects.hashCode(" evening ");
System.out.println(" In the morning hash value :"+hash_morning);// In the morning hash value :899331
System.out.println(" Evening hash value :"+hash_night);// Evening hash value :832240

}

Go on with our bucket , A bucket is every node in a linked list , You can also understand as a figure below in addition to tab On the entry ; Look at the picture

image.png

When the capacity of the bucket reaches a certain amount, it will turn into a red black tree , Look at the picture

 It's too hard ! This article HashMap Source code analysis , It can be called the Bible

It must have been a lot to see the readers here , It's just an appetizer , Let's get to the point of today , Source code analysis ;

2.4 put Method source code analysis

Test code

public static void main(String[] args) {
HashMap<String, Object> map = new HashMap<>();
map.put(" Early in the morning "," The baby cried ");
System.out.println(map);
}

The first entry is put The method includes putVal Method

public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);//
}

First pair key There was one hash Again as putVal Inside hash

static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

have a look putVal Method content , Because only one data is inserted , If the index is empty, it will not go else What's in it , The knowledge seeker here omits ;

You can see clearly that a node has been created (Node<K,V> It will be given below ) Put in tab in ,tab It's easy to understand , It's just a storage Node A list of ; Its index i = ( Capacity - 1) & hash value , It's essentially hash It's worth taking with the result , So it's a hash table ;

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {//evict =true
Node<K,V>[] tab; Node<K,V> p; int n, i;// Statement Tree array , Tree node ,n,i
if ((tab = table) == null || (n = tab.length) == 0)//table It's empty
n = (tab = resize()).length; // resize() yes Node<K,V>[] resize() n It's the length of the tree According to the initial capacity is n=16
if ((p = tab[i = (n - 1) & hash]) == null) // i = (16-1) & hash ---> 15 & 899342 = 14 ;
tab[i] = newNode(hash, key, value, null);// Create a new node , And insert data
else {
.......
}
++modCount;// Number of set structure modifications +1
if (++size > threshold)// size=1 ; threshold=12
resize();
afterNodeInsertion(evict);
return null;
}

I made a picture here to record

image.png

Node The code is as follows

static class Node<K,V> implements Map.Entry<K,V> {
final int hash;// Hash value key value Exclusive or hash value
final K key;// key
V value;// value
Node<K,V> next;// Store next node

Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
...........

The knowledge seeker added another night in , After running through the code, turn to the figure below

 It's too hard ! This article HashMap Source code analysis , It can be called the Bible

So knowledge seekers come up with an idea ,15 The binary of is 1111 , Any one of them key ,value After exclusive or of the hash value of Node The hash value of is the same as the original 1111 Meet each other That is to take Node The last four bits of the binary of the hash value shall prevail ;tab The capacity of is 16; Put in a Node after size Add 1, At most, it can only store 12 A value will increase capacity ; In this case as long as hash The same value will cause collision , And then you'll get into else Method , The problem arises , How to construct 2 Same. Node Hash value is a problem ; Here is an example :

Reference link :blog.csdn.net/hl_java/art…

public static void main(String[] args) {
System.out.println(HashMapTest.hash("Aa"));//2112
System.out.println(HashMapTest.hash("BB"));//2112
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

Keep on experimenting , Find out key Of hash After the same value , Will enter else Method , Will be in the original AA This Node Node properties next Add a node to store Bb; Wow, this is not the realization of a entry Are you on the list

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {//evict =true
Node<K,V>[] tab; Node<K,V> p; int n, i;// Statement Tree array , Tree node ,n,i
if ((tab = table) == null || (n = tab.length) == 0)//table It's empty
n = (tab = resize()).length; // resize() yes Node<K,V>[] resize() n Namely node The length of According to the initial capacity is n=16
if ((p = tab[i = (n - 1) & hash]) == null) // i = (16-1) & hash ---> 15 & Hash value
tab[i] = newNode(hash, key, value, null);// Create a new node , And insert data
else {
Node<K,V> e; K k; // Statement node k
if (p.hash == hash && // p This node Deposit Aa-->a ; hash 2112
((k = p.key) == key || (key != null && key.equals(k))))// here key The content is different, so I didn't enter , So it's not the same node
e = p;
else if (p instanceof TreeNode)// here p No TreeNode So I didn't go to the red and black tree Node
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) { // Default The number of barrels is 0
if ((e = p.next) == null) { // take p This Node The next node of is assigned to e by null; The beginning of the list
p.next = newNode(hash, key, value, null);// P Create node storage BB--> b
// among TREEIFY_THRESHOLD = 8
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);// The tree,
break;
}
if (e.hash == hash && // Here's the decision p and e Is it the same Node
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key

Last

Share a set of interview dry goods I sorted out , This document combines my years of interviewer experience , From the interviewer's point of view to tell you , The questions asked by the interviewer, what would he most like to hear from you , Share and help those friends who are confused about their future .

Interview experience skills

  • Experience and skill 1 How to answer the interviewer's questions skillfully
  • Experience and skill 2 How to answer technical questions
  • Experience and skill 3 How to answer non-technical questions
  • Experience and skill 4 How to answer quick estimate questions
  • Experience and skill 5 How to answer the problem of algorithm design
  • Experience and skill 6 How to answer system design questions
  • Experience and skill 7 How to solve the time conflict in job hunting
  • Experience and skill 8 If the interview question has ever met , Do you want to inform the interviewer
  • Experience and skill 9 Can I apply again after being rejected by the enterprise
  • Experience and skill 10 How to deal with the questions you won't answer
  • Experience and skill 11 How to deal with the interviewer's “ The method of agitation ” Language
  • Experience and skill 12 How to deal with the problem of holding different views with the interviewer
  • Experience and skill 13 What is workplace metaphor

 It's too hard ! This article HashMap Source code analysis , It can be called the Bible ,60 Minute quick grasp RabbitMQ

Interview questions

  • Detailed explanation of the real topic 1 A well-known Internet download service provider Software Engineer written test question
  • Detailed explanation of the real topic 2 A well-known social platform software engineer's written test question
  • Detailed explanation of the real topic 3 A well-known security software service provider Software Engineer written test question
  • Detailed explanation of the real topic 4 A well-known Internet Financial Enterprise Software Engineer written test question
  • Detailed explanation of the real topic 5 A well-known search engine provider Software Engineer written test question
  • Detailed explanation of the real topic 6 A written test for software engineers of a start-up company
  • Detailed explanation of the real topic 7 Written test questions for software engineers of a well-known game software development company
  • Detailed explanation of the real topic 8 Written test questions for software engineers of a well-known e-commerce company
  • Detailed explanation of the real topic 9 A top consumer website Software Engineer written test question
  • Detailed explanation of the real topic 10 A well-known portal software engineer written test question
  • Detailed explanation of the real topic 11 A well-known Internet Financial Enterprise Software Engineer written test question
  • Detailed explanation of the real topic 12 A well-known domestic network equipment provider Software Engineer written test question
  • Detailed explanation of the real topic 13 Written test questions for software engineers of a top mobile phone manufacturer in China
  • Detailed explanation of the real topic 14 Written test questions for software engineers of a top big data integrated service provider
  • Detailed explanation of the real topic 15 Written test questions for software engineers of a well-known social listed company
  • Detailed explanation of the real topic 16 Written test questions for software engineers of a well-known Internet company
  • Detailed explanation of the real topic 17 A well-known network security company campus recruitment technology pen test questions
  • Detailed explanation of the real topic 18 A well-known Internet game company campus recruitment, operation and maintenance development post pen test questions

 It's too hard ! This article HashMap Source code analysis , It can be called the Bible ,60 Minute quick grasp RabbitMQ

It's not easy to sort out the data , Pay attention before you go

This article has been  CODING Open source project :【 A big factory Java Analysis of interview questions + Core summary learning notes + The latest explanation video + Actual project source code 】 Included

版权声明:本文为[mb61ab40ce80d9c]所创,转载请带上原文链接,感谢。 https://javamana.com/2021/12/202112122307167184.html