当前位置:网站首页>HashSet underlying source code
HashSet underlying source code
2022-06-13 00:59:00 【-LM-】
Conclusion
- HashSet The bottom is HashMap
- When adding an element , First get hash value , Will be converted to index value
- Find the storage table table, Check whether there are existing elements at this index position
- without , Directly to join
- If there is , call equals Compare , If the same , Just give up adding , If it's not the same , Add to the last
- stay Java8 in , If the number of elements in a linked list exceeds TREEIFY_THRESHOLD( The default is 8), also table The size of is greater than or equal to MIN_TREEIFY_CAPACITY( The default is 64), It turns into a red black tree .
Inheritance system
Source code interpretation
1、 Constructors , Bottom use HashMap
public HashSet() {
map = new HashMap<>();
}
2、add Method , Call to HashMap Of put Method
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
3、 perform put Method ,key It's an incoming parameter ,value It's a Object object , placeholder , Don't put anything , Always the same
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
4、 Calculation hash value , obtain key Corresponding hash value , Not equivalent to hashcode
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
5、 Get into putval Method
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i; // Define auxiliary variables
// if Statement indicates if the current table yes null, Or the size is 0, For the first time , To 16 Space
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// according to key, Got hash value , Calculation key It should be stored in table Which index position of the table , Assign the position of the object to p
// Judge p Is it empty , If it is empty, it means that the element has not been placed , Just create one Node
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
// If p Not empty , Prove that the element has been placed
Node<K,V> e; K k;
// If the first element of the linked list corresponding to the current index position and the key Of hash Same value
// And meet the needs of those who are ready to join key and p Point to the Node Node key Is the same object perhaps Same content
// Can't join
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// To determine p Is it a red black tree
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); // If it's a red-black tree , call putTreeVal add to
else {
// If table The corresponding index position is a linked list , Traverse the linked list to judge
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
// It is different from each element of the linked list , Then add to the end of the linked list
p.next = newNode(hash, key, value, null);
// Add to the linked list , Immediately judge whether the linked list has reached 8 Nodes , Reached 8 Tree nodes
// Whether it is really treelized , You also need to determine whether the length of the table exceeds 64, Less than 64 Just expand the capacity of the array
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// Compare in turn , If there is the same direct break
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// If this value exists, the old value will be returned
if (e != null) {
// existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//size Every time you add a node ,size I'll add one
if (++size > threshold) // Judge whether to expand capacity
resize();
afterNodeInsertion(evict); // Subclasses use ,HashMap It's an empty method
return null;
}
Expansion mechanism
HashSet The bottom is HashMap, The first time I added it ,table Expand the array to 16, The critical value is 16* Load factor ( The default is 0.75), Reach the critical value for capacity expansion
边栏推荐
- Key point detection data preparation and model design based on u-net Network -- detection model of four key points of industrial components
- [JS component] customize the right-click menu
- [virtual machine] notes on virtual machine environment problems
- Wal mechanism of MySQL
- Common skills for quantitative investment - drawing 3: drawing the golden section line
- Andersen Global通过在芬兰和丹麦的合作协议拓展北欧地区业务版图
- Canvas airplane game
- Remove duplicates from an ordered array
- Opencv desaturation
- STM32 USB Basics
猜你喜欢
(01).NET MAUI实战 建项目
Wal mechanism of MySQL
Kotlin collaboration, the life cycle of a job
Mysql database password modification
[JS component] floating text
Quantitative investment traditional index investment decision vs Monte Carlo simulation method
How to choose stocks? Which indicator strategy is reliable? Quantitative analysis and comparison of strategic benefits of ASI, VR, arbr, DPO and trix indicators
Four startup modes of kotlin collaboration
Build your own PE manually from winpe of ADK
今日睡眠质量记录74分
随机推荐
Today's sleep quality record 74 points
redis
Remove duplicates from an ordered array
kotlin 协程withContext切换线程
Kotlin 协程的四种启动模式
Androi天氣
Dynamic planning - good article link
[JS component] calendar
Et5.0 simply transform referencecollectorieditor
Quick power explanation
[network protocol] problems and solutions in the use of LwIP
The scope builder coroutinescope, runblocking and supervisorscope of kotlin collaboration processes run synchronously. How can other collaboration processes not be suspended when the collaboration pro
Comparison of disk partition modes (MBR and GPT)
刘徽与《九章算术》《海岛算经》简介
[JS component library] drag sorting component
草在结种子了
单片机串口中断以及消息收发处理——对接受信息进行判断实现控制
Can GPU acceleration pytorch work?
【服务器数据恢复】存储服务器之间迁移数据时数据丢失恢复成功案例
[JS component] customize the right-click menu