Welcome to mirror list, hosted at ThFree Co, Russian Federation.

index.html « hashmap « collections - github.com/xiaoheiAh/hugo-theme-pure.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6f6ff150efe5b9501dd49b94467a7b3e3d5608e9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <title>
        Collections-Hashmap - 赵小黑的博客
      </title>
    <head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport"
    content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  
  <meta name="theme-color" content="#000000" />
  
  <meta http-equiv="window-target" content="_top" />
  
  
  <meta name="description" content="" />
  <meta name="generator" content="Hugo 0.58.0 with theme pure" />
  <title>Collections-Hashmap - 赵小黑的博客</title>
  

  <link rel="stylesheet" href="https://xiaohei.im/hugo-theme-pure/css/style.css">
  <link rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/9.15.10/styles/github.min.css"> 
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.css">
  <meta property="og:title" content="Collections-Hashmap" />
<meta property="og:description" content="" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://xiaohei.im/hugo-theme-pure/collections/hashmap/" />
<meta property="article:published_time" content="2019-08-15T13:19:18+08:00" />
<meta property="article:modified_time" content="2019-08-15T13:19:18+08:00" />
<meta itemprop="name" content="Collections-Hashmap">
<meta itemprop="description" content="">


<meta itemprop="datePublished" content="2019-08-15T13:19:18&#43;08:00" />
<meta itemprop="dateModified" content="2019-08-15T13:19:18&#43;08:00" />
<meta itemprop="wordCount" content="6419">



<meta itemprop="keywords" content="collections," />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Collections-Hashmap"/>
<meta name="twitter:description" content=""/>

  <!--[if lte IE 9]>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
    <![endif]-->

  <!--[if lt IE 9]>
      <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
    <![endif]-->

</head>
  </head>
  

  <body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage"><header class="header" itemscope itemtype="http://schema.org/WPHeader">
    <div class="slimContent">
      <div class="navbar-header">
        <div class="profile-block text-center">
          <a id="avatar" href="https://github.com/xiaoheiAh" target="_blank">
            <img class="img-circle img-rotate" src="https://xiaohei.im/hugo-theme-pure/avatar.png" width="200" height="200">
          </a>
          <h2 id="name" class="hidden-xs hidden-sm">赵小黑</h2>
          <h3 id="title" class="hidden-xs hidden-sm hidden-md">Java Developer</h3>
          <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i>Shanghai, China</small>
        </div><div class="search" id="search-form-wrap">
    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="搜索" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i
                        class="icon icon-search"></i></button>
            </span>
        </div>
        <div class="ins-search">
            <div class="ins-search-mask"></div>
            <div class="ins-search-container">
                <div class="ins-input-wrapper">
                    <input type="text" class="ins-search-input" placeholder="想要查找什么..."
                        x-webkit-speech />
                    <button type="button" class="close ins-close ins-selectable" data-dismiss="modal"
                        aria-label="Close"><span aria-hidden="true">×</span></button>
                </div>
                <div class="ins-section-wrapper">
                    <div class="ins-section-container"></div>
                </div>
            </div>
        </div>
    </form>
</div>
        <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>
      <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
        <ul class="nav navbar-nav main-nav  menu-highlight">
            <li class="menu-item menu-item-home">
                <a href="/hugo-theme-pure/">
                    <i class="icon icon-home-fill"></i>
                  <span class="menu-title">主页</span>
                </a>
            </li>
            <li class="menu-item menu-item-archives">
                <a href="/hugo-theme-pure/posts">
                    <i class="icon icon-archives-fill"></i>
                  <span class="menu-title">归档</span>
                </a>
            </li>
            <li class="menu-item menu-item-categories">
                <a href="/hugo-theme-pure/categories">
                    <i class="icon icon-folder"></i>
                  <span class="menu-title">分类</span>
                </a>
            </li>
            <li class="menu-item menu-item-tags">
                <a href="/hugo-theme-pure/tags">
                    <i class="icon icon-tags"></i>
                  <span class="menu-title">标签</span>
                </a>
            </li>
            <li class="menu-item menu-item-about">
                <a href="/hugo-theme-pure/about">
                    <i class="icon icon-cup-fill"></i>
                  <span class="menu-title">关于</span>
                </a>
            </li>
        </ul>
      </nav>
    </div>
  </header>
  <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">公告</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content"><p>自用科学上网节点推荐(便宜又好用)<a href="https://tianlinzhao.com/aff.php?aff=4969" target="_blank" style="background-color:#FFFF00">点这里跳转</a>
            </div>
        </div>
    </div>
</div>

      <div class="widget">
    <h3 class="widget-title"> 分类</h3>
    <div class="widget-body">
        <ul class="category-list">
            <li class="category-list-item"><a href="https://xiaohei.im/hugo-theme-pure/categories/corejava/" class="category-list-link">corejava</a><span class="category-list-count">7</span></li>
            <li class="category-list-item"><a href="https://xiaohei.im/hugo-theme-pure/categories/hystrix/" class="category-list-link">hystrix</a><span class="category-list-count">2</span></li>
            <li class="category-list-item"><a href="https://xiaohei.im/hugo-theme-pure/categories/leetcode/" class="category-list-link">leetcode</a><span class="category-list-count">3</span></li>
            <li class="category-list-item"><a href="https://xiaohei.im/hugo-theme-pure/categories/redis/" class="category-list-link">redis</a><span class="category-list-count">10</span></li>
            <li class="category-list-item"><a href="https://xiaohei.im/hugo-theme-pure/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" class="category-list-link">学习笔记</a><span class="category-list-count">1</span></li>
            <li class="category-list-item"><a href="https://xiaohei.im/hugo-theme-pure/categories/%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/" class="category-list-link">消息队列</a><span class="category-list-count">4</span></li>
        </ul>
    </div>
</div>
      <div class="widget">
    <h3 class="widget-title"> 标签</h3>
    <div class="widget-body">
        <ul class="tag-list">
            
            
            <li class="tag-list-item"><a href="https://xiaohei.im/hugo-theme-pure/tags/collections/" class="tag-list-link">collections</a><span
                    class="tag-list-count">7</span></li>
            
            
            <li class="tag-list-item"><a href="https://xiaohei.im/hugo-theme-pure/tags/hugo/" class="tag-list-link">hugo</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://xiaohei.im/hugo-theme-pure/tags/hystrix/" class="tag-list-link">hystrix</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://xiaohei.im/hugo-theme-pure/tags/leetcode/" class="tag-list-link">leetcode</a><span
                    class="tag-list-count">3</span></li>
            
            
            <li class="tag-list-item"><a href="https://xiaohei.im/hugo-theme-pure/tags/netty/" class="tag-list-link">netty</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://xiaohei.im/hugo-theme-pure/tags/rabbitmq/" class="tag-list-link">rabbitmq</a><span
                    class="tag-list-count">4</span></li>
            
            
            <li class="tag-list-item"><a href="https://xiaohei.im/hugo-theme-pure/tags/redis/" class="tag-list-link">redis</a><span
                    class="tag-list-count">10</span></li>
            
            
            <li class="tag-list-item"><a href="https://xiaohei.im/hugo-theme-pure/tags/rust/" class="tag-list-link">rust</a><span
                    class="tag-list-count">3</span></li>
            
            
            <li class="tag-list-item"><a href="https://xiaohei.im/hugo-theme-pure/tags/rxjava/" class="tag-list-link">rxjava</a><span
                    class="tag-list-count">2</span></li>
            
            
            <li class="tag-list-item"><a href="https://xiaohei.im/hugo-theme-pure/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/" class="tag-list-link">分布式锁</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://xiaohei.im/hugo-theme-pure/tags/%E5%93%8D%E5%BA%94%E5%BC%8F%E7%BC%96%E7%A8%8B/" class="tag-list-link">响应式编程</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://xiaohei.im/hugo-theme-pure/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" class="tag-list-link">数据结构</a><span
                    class="tag-list-count">1</span></li>
            
        </ul>

    </div>
</div>
      
<div class="widget">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget-body">
        <ul class="recent-post-list list-unstyled no-thumbnail">
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://xiaohei.im/hugo-theme-pure/2019/11/netty/" class="title">[学习笔记] Netty</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2019-11-29 18:40:27 &#43;0800 CST" itemprop="datePublished">2019-11-29</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://xiaohei.im/hugo-theme-pure/2019/11/cluster/" class="title">Redis HA - Cluster</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2019-11-24 11:48:17 &#43;0800 CST" itemprop="datePublished">2019-11-24</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://xiaohei.im/hugo-theme-pure/2019/11/sentinel/" class="title">Redis HA - 哨兵模式</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2019-11-23 17:56:15 &#43;0800 CST" itemprop="datePublished">2019-11-23</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://xiaohei.im/hugo-theme-pure/2019/11/replication/" class="title">Redis-复制功能探索</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2019-11-16 14:24:40 &#43;0800 CST" itemprop="datePublished">2019-11-16</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://xiaohei.im/hugo-theme-pure/2019/11/event/" class="title">Redis-事件</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2019-11-14 15:01:45 &#43;0800 CST" itemprop="datePublished">2019-11-14</time>
                    </p>
                </div>
            </li>
        </ul>
    </div>
</div>
  </div>
</aside>

    
    
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <h4 class="toc-title">文章目录</h4>
    <nav id="toc" class="js-toc toc">

    </nav>
  </div>
</aside>
<main class="main" role="main"><div class="content">
  <article id="-" class="article article-type-" itemscope
    itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      <h1 itemprop="name">
  <a
    class="article-title"
    href="/hugo-theme-pure/collections/hashmap/"
    >Collections-Hashmap</a
  >
</h1>

      <div class="article-meta">
        <span class="article-date">
  <i class="icon icon-calendar-check"></i>
<a href="https://xiaohei.im/hugo-theme-pure/collections/hashmap/" class="article-date">
  <time datetime="2019-08-15 13:19:18 &#43;0800 CST" itemprop="datePublished">2019-08-15</time>
</a>
</span><span class="article-category">
  <i class="icon icon-folder"></i>
  <a class="article-category-link" href="/hugo-theme-pure/categories/corejava/"> CoreJava </a>
</span>  
  <span class="article-tag">
    <i class="icon icon-tags"></i>
    <a class="article-tag-link" href="/hugo-theme-pure/tags/collections/"> collections </a>
  </span>

	<span class="article-read hidden-xs">
	    <i class="icon icon-eye-fill" aria-hidden="true"></i>
	    <span id="busuanzi_container_page_pv">
			<span id="busuanzi_value_page_pv">0</span>
		</span>
	</span>
        <span class="post-comment"><i class="icon icon-comment"></i> <a href="/hugo-theme-pure/collections/hashmap/#comments"
            class="article-comment-link">评论</a></span>
		<span class="post-wordcount hidden-xs" itemprop="wordCount">字数统计:6419字</span>
		<span class="post-readcount hidden-xs" itemprop="timeRequired">阅读时长:13分 </span>
      </div>
    </div>
    <div class="article-entry marked-body js-toc-content" itemprop="articleBody">
      <blockquote>
<p>美团的blog:<a href="https://tech.meituan.com/java_hashmap.html">https://tech.meituan.com/java_hashmap.html</a>
参考blog: <a href="https://www.tianxiaobo.com/2018/01/18/HashMap-%E6%BA%90%E7%A0%81%E8%AF%A6%E7%BB%86%E5%88%86%E6%9E%90-JDK1-8/">田小波的博客</a>
<a href="https://www.tianxiaobo.com/2018/01/11/%E7%BA%A2%E9%BB%91%E6%A0%91%E8%AF%A6%E7%BB%86%E5%88%86%E6%9E%90/">红黑树介绍</a></p>
</blockquote>

<h2 id="hashmap-hashtable-concurrenthashmap的区别">HashMap,HashTable,ConcurrentHashMap的区别?</h2>

<p><strong>HashMap</strong>是非线程安全的,<strong>HashTable</strong>和<strong>ConcurrentHashMap</strong>是线程安全的.HashTable不允许null key和null Value,HashMap允许.
ConcurrentHashMap推出之后官方推荐不要在使用HashTable作为线程安全的使用类,而是使用这个.关于<strong>ConcurrentHashMap</strong>后面再学习.
&gt; <a href="https://juejin.im/post/5add97a46fb9a07aa212f4c0">参考blog</a></p>

<h2 id="hashmap在不同版本之间实现的区别">HashMap在不同版本之间实现的区别?</h2>

<blockquote>
<p><a href="http://linfenliang.com/hashmap/2017/08/04/HashMapInJDK-6-7-8-Differ/">区别</a></p>
</blockquote>

<h2 id="官方文档介绍">官方文档介绍:</h2>

<ol>
<li>基于<code>Map</code>接口实现的哈希表.提供了所有map可选的操作,允许key为null,value为null.<code>HashMap</code>与<code>HashTable</code>基本一致,除了<code>HashMap</code> <em>线程不安全并且允许为空</em>.
不保证有序,尤其不保证顺序一直不变(因为扩容时会rehash,基本上就顺序就重排了)</li>
<li>假设hash分布均匀的情况下,基本的操作(<code>get/put</code>)性能很不错.迭代所需要的时间与<code>buckets</code>数量与每个<code>bukets</code>下的键值对的数量之和成正比.所以官方建议如果要求hashmap的迭代性能的话,初始的<code>capacity</code>不能太高,<code>loadFactor</code>不要太高.</li>

<li><p>HashMap有两个重要的参数:<code>initial capacity</code>,<code>load factor</code>.capacity定义bucket的数量,initial capacity定义的是初始化bucket数量.load factor(中文名: <em>加载因子</em> )是判断哈希表是否需要扩容的阈值,当entries数量超过(load factor * current capacity),哈希表会触发<code>rehash</code>操作,内部数据结构会重整,buckets数量会变为之前大约两倍左右</p></li>

<li><p>通常情况下,load factor 默认<code>0.75f</code>,在时间空间上是很平衡的.值偏高时,空间减少,查找时间上升了(影响大部分的操作,get/put之类的),在设置初始容量时,需要考虑到预期的entries数量和加载因子,以便最小化rehash的数量.如果初始化的容量大于最大数量的entries除以加载因子,不会发生rehash操作.</p></li>

<li><p>如果有大量的键值对存到hashmap中,那么创建一个足够大的hashmap来存储要比让他自动rehash扩容来存储的性能要好很多.注意:具有相同hashcode的多个key肯定会影响哈希表的性能.为了改善这种影响,当key是Comparable类型时,可以通过key之间的比较顺序来打破这种关系.</p></li>

<li><p>注意hashmap是<code>Non synchronized</code>,即 <em>非线程安全</em>.如果多线程并发访问hashmap,并且至少有一个线程操作map的结构,在外部必须<code>synchronized</code>.(结构修改是指任何关于add或delte的操作,仅仅只是修改key关联的value时则不属于结构修改).通常在将object封装进map做synchronized操作</p></li>

<li><p>如果不存在上面的objects,那这个map需要被Collections.synchronizedMap包装下.最好在创建的时候就做好,防止偶然的并发访问.</p>

<pre><code class="language-java">Map m = Collections.synchronizedMap(new HashMap(...));
</code></pre></li>

<li><p>迭代器的所有方法都是<code>fail-fast</code>,如果迭代器创建后,在迭代器里的结构操作必须通过迭代器的方法来操作,否则会抛<code>ConcurrentModificationException</code>.因此,面对并发修改,迭代器会快速而干净的失败,而不是在未来的不确定时间冒任意非确定行为的风险.</p></li>

<li><p>请注意,迭代器的快速失败行为无法得到保证,因为一般来说,在存在不同步的并发修改时,不可能做出任何硬性保证. 快速失败迭代器会尽最大努力抛出ConcurrentModificationException. 因此,编写依赖于此异常的程序以确保其正确性是错误的:迭代器的快速失败行为应该仅用于检测错误.</p></li>
</ol>

<h2 id="源码">源码</h2>

<pre><code class="language-java">    /**
     * The default initial capacity - MUST be a power of two.
     * 默认的容量16 必须是2的n次方
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 &lt;&lt; 4; // aka 16

    /**
     * 最大的容量限制
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two &lt;= 1&lt;&lt;30.
     */
    static final int MAXIMUM_CAPACITY = 1 &lt;&lt; 30;

    /**
     * 默认的加载因子
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    /**
     * 大于这个值转红黑树
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * 大于这个值小于 TREEIFY_THRESHOLD 不转树
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * hashmap整体容量大于这个值时才能树化
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     */
    static final int MIN_TREEIFY_CAPACITY = 64;
    
    /**
     * node节点
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
    static class Node&lt;K,V&gt; implements Map.Entry&lt;K,V&gt; {
        final int hash;
        final K key;
        V value;
        Node&lt;K,V&gt; next;

        Node(int hash, K key, V value, Node&lt;K,V&gt; next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + &quot;=&quot; + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }
	
        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&lt;?,?&gt; e = (Map.Entry&lt;?,?&gt;)o;
                if (Objects.equals(key, e.getKey()) &amp;&amp;
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

    //hashMap中的静态方法
    /**
     * hash方法详解 blog:http://www.hollischuang.com/archives/2091
     * 扰动算法--使hash分布更均匀
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h &gt;&gt;&gt; 16);
    }
    
    //取模运算,获得对象存储到bukets的下标
    //实际上就是取模,一般取模使用% 但是考虑到效率问题,采用位运算
    //X % 2^n = X &amp; (2^n-1) 这也是为什么hashmap容量为2的n次方的原因
    static int indexFor(int h, int length) {
	return h &amp; (length-1);
    }
    //返回hashmap的容量 2的n次方 很巧妙的位运算
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n &gt;&gt;&gt; 1;
        n |= n &gt;&gt;&gt; 2;
        n |= n &gt;&gt;&gt; 4;
        n |= n &gt;&gt;&gt; 8;
        n |= n &gt;&gt;&gt; 16;
        return (n &lt; 0) ? 1 : (n &gt;= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
    
    /**
     * 参数都用transient不让序列化的原因:https://segmentfault.com/q/1010000000630486
     */

    //bukets hashmap是链表加数组的结构.此为数组
    transient Node&lt;K,V&gt;[] table;
    
    //保存键值对的Entry
    transient Set&lt;Map.Entry&lt;K,V&gt;&gt; entrySet;
    
    //hashmap的size
    transient int size;
    
    //结构操作次数 可用于快速失败的比较条件 例如并发操作时
    transient int modCount;
    
    //resize的临界点: capacity * load factor 
    int threshold;
    
    //加载因子
    final float loadFactor;

    //公有操作方法

    //构造方法
    /**
     * 根据 initial capactity 和 loadFactor创建空的hashmap
     * Constructs an empty &lt;tt&gt;HashMap&lt;/tt&gt; 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) {
	//校验initialCapacity
        if (initialCapacity &lt; 0)
            throw new IllegalArgumentException(&quot;Illegal initial capacity: &quot; +
                                               initialCapacity);
	//容量校验
        if (initialCapacity &gt; MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
	//校验loadFactor isNaN--&gt; 是否是一个number Not-a-Number
        if (loadFactor &lt;= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException(&quot;Illegal load factor: &quot; +
                                               loadFactor);
	//加载因子赋值
        this.loadFactor = loadFactor;
	//扩容阈值赋值 2的n次方
        this.threshold = tableSizeFor(initialCapacity);
    }

    /**
     * 通过initialCapacity赋值
     * Constructs an empty &lt;tt&gt;HashMap&lt;/tt&gt; 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);
    }
    
    /**
     * 根据默认容量和默认加载因子创建空的hashmap
     * Constructs an empty &lt;tt&gt;HashMap&lt;/tt&gt; with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    /**
     * 根据传进来的map创建一个新的hashMap 
     * initialCapacity 足以装下参数map的数量
     * loadFactor使用默认值
     * Constructs a new &lt;tt&gt;HashMap&lt;/tt&gt; with the same mappings as the
     * specified &lt;tt&gt;Map&lt;/tt&gt;.  The &lt;tt&gt;HashMap&lt;/tt&gt; is created with
     * default load factor (0.75) and an initial capacity sufficient to
     * hold the mappings in the specified &lt;tt&gt;Map&lt;/tt&gt;.
     *
     * @param   m the map whose mappings are to be placed in this map
     * @throws  NullPointerException if the specified map is null
     */
    public HashMap(Map&lt;? extends K, ? extends V&gt; 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).
     * evict 初始化构建map时 为false 其他情况下为true
     */
    final void putMapEntries(Map&lt;? extends K, ? extends V&gt; m, boolean evict) {
        int s = m.size();
        if (s &gt; 0) {
	    //初次创建hashmap
            if (table == null) { // pre-size
		//计算m所需要的容量
                float ft = ((float)s / loadFactor) + 1.0F;
		//获得真实的容量
                int t = ((ft &lt; (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
		//如果比默认的阈值大则计算该 t 对应的capacity
                if (t &gt; threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s &gt; threshold) // 如果是table不为null 即是后续往map中添加 如果s &gt; 阈值就要重置map了
                resize();//resize操作 后面介绍
	    //确定容量后put操作
            for (Map.Entry&lt;? extends K, ? extends V&gt; e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);//
            }
        }
    }

    /*主要调用 putVal */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * put 操作
     * 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 不存在才put&lt;D-[&gt;
     * @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&lt;K,V&gt;[] tab; Node&lt;K,V&gt; p; int n, i;
	//若是新建map的情况下 resize创建指定长度的table 
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
	//取模计算该key对应的数组下标 并判断该坐标下的对象是否为null
	//为null时创建一个新node存入tab[i]
        if ((p = tab[i = (n - 1) &amp; hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {//tab[i] != null
            Node&lt;K,V&gt; e; K k;
	    //如果p与存入的key完全相同
            if (p.hash == hash &amp;&amp;
                ((k = p.key) == key || (key != null &amp;&amp; key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
		//如果是红黑树节点 调用putTreeVal
                e = ((TreeNode&lt;K,V&gt;)p).putTreeVal(this, tab, hash, key, value);
            else {
		//普通的put
		//binCount记录了链表的长度
                for (int binCount = 0; ; ++binCount) {
		    //如果当前node的next==null说明就可以往该链上添加一个节点
                    if ((e = p.next) == null) {
			//新建node接到p.next下面
                        p.next = newNode(hash, key, value, null);
			//如果binCount大于设定的红黑树化阈值
                        if (binCount &gt;= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);//红黑树化
                        break;
                    }
		    //如果key与链表中的任意node完全相同break
                    if (e.hash == hash &amp;&amp;
                        ((k = e.key) == key || (key != null &amp;&amp; key.equals(k))))
                        break;
                    p = e;
                }
            }
	    //如果存在该key
            if (e != null) { // existing mapping for key
                V oldValue = e.value;//获得旧值
                if (!onlyIfAbsent || oldValue == null)//若没有设置不存在才put或者oldValue=null
                    e.value = value;//赋新值
                afterNodeAccess(e);//LinkedHashMap操作
                return oldValue;//返回旧值
            }
        }
        ++modCount;
        if (++size &gt; threshold)//是否需要扩容
            resize();
        afterNodeInsertion(evict);//LinkedHashMap操作
        return null;
    }

    /**
     * 扩容操作
     * 若是初始化则根据initialCapacity创建一个table
     * 否则,扩容为2的n次方倍
     * 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&lt;K,V&gt;[] resize() {
        Node&lt;K,V&gt;[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap &gt; 0) {
	    //超过最大值不会再扩容了
            if (oldCap &gt;= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            else if ((newCap = oldCap &lt;&lt; 1) &lt; MAXIMUM_CAPACITY &amp;&amp;
                     oldCap &gt;= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr &lt;&lt; 1; // double threshold 扩成两倍
        }
        else if (oldThr &gt; 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 &lt; MAXIMUM_CAPACITY &amp;&amp; ft &lt; (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({&quot;rawtypes&quot;,&quot;unchecked&quot;})
            Node&lt;K,V&gt;[] newTab = (Node&lt;K,V&gt;[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
	    //把old buket 移到新的bukets里
            for (int j = 0; j &lt; oldCap; ++j) {
                Node&lt;K,V&gt; e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)//直接添加
                        newTab[e.hash &amp; (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        ((TreeNode&lt;K,V&gt;)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node&lt;K,V&gt; loHead = null, loTail = null;
                        Node&lt;K,V&gt; hiHead = null, hiTail = null;
                        Node&lt;K,V&gt; next;
                        do {
                            next = e.next;
			    //这个取模很精辟 请结合美团的blog resize 1.8优化学习
			    //因为扩容是2倍扩容,二进制中相当于左移一位
			    /**
			     * 假设一次扩容		    
			     * 扩容前	oldCap = 00010000   oldCap - 1 = 00001111
			     * 扩容后	newCap = 00100000   newCap - 1 = 00011111
			     * 可以看出扩容后 newCap-1 在高位多了1
			     * 计算index时 hash &amp; n-1 = 原位置 + oldCap
			     * 所以只需要判断hash &amp; oldCap是否为1
			     * 为1则把该node的位置移到 oldCap+原位置 
			     * 为 0 还在原位置
			     */
                            if ((e.hash &amp; oldCap) == 0) {//为0说明位置没有变
                                if (loTail == null)//第一次添加时loHead=e
                                    loHead = e;
                                else
                                    loTail.next = e;//直接往后插入
                                loTail = e;
                            }
                            else {//为1 说明位置会+oldCap长度
                                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) {//放在原位置+oldCap上
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

    /**
     * get操作
     * 为null时返回null 这个要注意下
     */
    public V get(Object key) {
        Node&lt;K,V&gt; e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }


    /**
     * Implements Map.get and related methods
     * get方法
     * 主要是   key相等 或者 key equals的比较
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    final Node&lt;K,V&gt; getNode(int hash, Object key) {
        Node&lt;K,V&gt;[] tab; Node&lt;K,V&gt; first, e; int n; K k;
        if ((tab = table) != null &amp;&amp; (n = tab.length) &gt; 0 &amp;&amp;
            (first = tab[(n - 1) &amp; hash]) != null) {//获得节点
            if (first.hash == hash &amp;&amp; // always check first node
                ((k = first.key) == key || (key != null &amp;&amp; key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)//树节点
                    return ((TreeNode&lt;K,V&gt;)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &amp;&amp;
                        ((k = e.key) == key || (key != null &amp;&amp; key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }




</code></pre>

<h2 id="1-8红黑树化源码解析">1.8红黑树化源码解析</h2>

<pre><code class="language-java">    /**
     * TreeNode extends LinkedHashMap.Entry
     * LinkedHashMap.Entry extends HashMap.Node
     */

    static final class TreeNode&lt;K,V&gt; extends LinkedHashMap.Entry&lt;K,V&gt; {
        TreeNode&lt;K,V&gt; parent;  // red-black tree links 红黑树父节点
        TreeNode&lt;K,V&gt; left;
        TreeNode&lt;K,V&gt; right;
        TreeNode&lt;K,V&gt; prev;    // needed to unlink next upon deletion 删除的时候用来连接前后
        boolean red;//红还是黑
        TreeNode(int hash, K key, V val, Node&lt;K,V&gt; next) {
            super(hash, key, val, next);
        }
    }     
    
    
    /**树化
     * putVal里有用到
     * 将链表重置为红黑树并放到该hash映射的tab下,如果tab过下则resize
     * 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&lt;K,V&gt;[] tab, int hash) {
        int n, index; Node&lt;K,V&gt; e;
        if (tab == null || (n = tab.length) &lt; MIN_TREEIFY_CAPACITY)//小于最小树化的容量时不树化而resize  capacity为64,
            resize();
        else if ((e = tab[index = (n - 1) &amp; hash]) != null) {
            TreeNode&lt;K,V&gt; hd = null, tl = null;//头尾节点
            do {
                TreeNode&lt;K,V&gt; p = replacementTreeNode(e, null);//这个就是返回一个新建的TreeNode对象,内容为e
                if (tl == null)//确定是头结点
                    hd = p;//标记头结点
                else {//非头结点就首尾连接
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;//尾节点一直为p
            } while ((e = e.next) != null);//遍历链表 其实此时形成也还算是个链表
            if ((tab[index] = hd) != null)//将该treeNode挂到table下
                hd.treeify(tab);//完成红黑树化
        }
    }

       /**
         * Forms tree of the nodes linked from this node.
         * @return root of tree
         */
        final void treeify(Node&lt;K,V&gt;[] tab) {
            TreeNode&lt;K,V&gt; root = null;
            for (TreeNode&lt;K,V&gt; x = this, next; x != null; x = next) {//x 从当前节点开始(从treeifyBin里调用看是头结点)
                next = (TreeNode&lt;K,V&gt;)x.next;//获取下个节点
                x.left = x.right = null;
                if (root == null) {//设置root节点并给他黑色
                    x.parent = null;
                    x.red = false;
                    root = x;
                }
                else {
                    K k = x.key;
                    int h = x.hash;
                    Class&lt;?&gt; kc = null;
                    //遍历所有节点与当前节点x比较 调整位置 有点像冒泡排序
                    for (TreeNode&lt;K,V&gt; p = root;;) {
                        int dir, ph;
                        K pk = p.key;
                        //比较hash值
                        if ((ph = p.hash) &gt; h)
                            dir = -1;
                        else if (ph &lt; h)
                            dir = 1;
                        else if ((kc == null &amp;&amp;
                                  (kc = comparableClassFor(k)) == null) ||
                                 (dir = compareComparables(kc, k, pk)) == 0)
                            dir = tieBreakOrder(k, pk);
                        
                        //根据dir判断x是p的左孩子 还是 右孩子
                        TreeNode&lt;K,V&gt; xp = p;
                        if ((p = (dir &lt;= 0) ? p.left : p.right) == null) {
                            x.parent = xp;
                            if (dir &lt;= 0)
                                xp.left = x;
                            else
                                xp.right = x;
                            //平衡节点
                            root = balanceInsertion(root, x);
                            break;
                        }
                    }
                }
            }
            moveRootToFront(tab, root);
        }

        /**
         * Returns a list of non-TreeNodes replacing those linked from
         * this node.
         */
        final Node&lt;K,V&gt; untreeify(HashMap&lt;K,V&gt; map) {
            Node&lt;K,V&gt; hd = null, tl = null;
            for (Node&lt;K,V&gt; q = this; q != null; q = q.next) {
                Node&lt;K,V&gt; p = map.replacementNode(q, null);
                if (tl == null)
                    hd = p;
                else
                    tl.next = p;
                tl = p;
            }
            return hd;
        }

        /**
         * 红黑树版put操作
         * Tree version of putVal.
         */
        final TreeNode&lt;K,V&gt; putTreeVal(HashMap&lt;K,V&gt; map, Node&lt;K,V&gt;[] tab,
                                       int h, K k, V v) {
            Class&lt;?&gt; kc = null;
            boolean searched = false;
            TreeNode&lt;K,V&gt; root = (parent != null) ? root() : this;//每次从根节点遍历
            for (TreeNode&lt;K,V&gt; p = root;;) {
                int dir, ph; K pk;
                if ((ph = p.hash) &gt; h)
                    dir = -1;
                else if (ph &lt; h)
                    dir = 1;
                else if ((pk = p.key) == k || (k != null &amp;&amp; k.equals(pk)))
                    //如果当前节点key相同或equals 返回
                    return p;
                else if ((kc == null &amp;&amp;
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) {
                    //hash值如果相等 但类不相同,只能挨个对比左右孩子
                    if (!searched) {
                        TreeNode&lt;K,V&gt; q, ch;
                        searched = true;
                        if (((ch = p.left) != null &amp;&amp;
                             (q = ch.find(h, k, kc)) != null) ||
                            ((ch = p.right) != null &amp;&amp;
                             (q = ch.find(h, k, kc)) != null))
                            return q;
                    }
                    //哈希值相等 但键无法比较 只能通过其他方法比较
                    dir = tieBreakOrder(k, pk);
                }

                //得到两个节点的大小关系 即dir的值时
                //并判断只有在左孩子或右孩子不能
                TreeNode&lt;K,V&gt; xp = p;
                if ((p = (dir &lt;= 0) ? p.left : p.right) == null) {
                    Node&lt;K,V&gt; xpn = xp.next;
                    TreeNode&lt;K,V&gt; x = map.newTreeNode(h, k, v, xpn);
                    if (dir &lt;= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    xp.next = x;
                    x.parent = x.prev = xp;
                    if (xpn != null)
                        ((TreeNode&lt;K,V&gt;)xpn).prev = x;
                    //平衡二叉树
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }

        /** 查找操作 传入 hash值 和 key值
         * Calls find for root node.
         */
        final TreeNode&lt;K,V&gt; getTreeNode(int h, Object k) {
            return ((parent != null) ? root() : this).find(h, k, null);//判断从当前节点还是root节点开始查找
        }


        /**
         * Finds the node starting at root p with the given hash and key.
         * The kc argument caches comparableClassFor(key) upon first use
         * comparing keys.
         */
        final TreeNode&lt;K,V&gt; find(int h, Object k, Class&lt;?&gt; kc) {
            TreeNode&lt;K,V&gt; p = this;
            do {
                int ph, dir; K pk;
                TreeNode&lt;K,V&gt; pl = p.left, pr = p.right, q;
                //根据hash值查找 当前节点hash值大于h则 查左孩子 否则右孩子 当key相等或者equal时返回
                if ((ph = p.hash) &gt; h)
                    p = pl;
                else if (ph &lt; h)
                    p = pr;
                else if ((pk = p.key) == k || (k != null &amp;&amp; k.equals(pk)))
                    return p;
                else if (pl == null)
                    p = pr;
                else if (pr == null)
                    p = pl;
                else if ((kc != null ||
                          (kc = comparableClassFor(k)) != null) &amp;&amp;
                         (dir = compareComparables(kc, k, pk)) != 0)
                    p = (dir &lt; 0) ? pl : pr;
                else if ((q = pr.find(h, k, kc)) != null)//不相等则从子树继续查找
                    return q;
                else
                    p = pl;
            } while (p != null);
            return null;
        }

</code></pre>
    </div>
    <div class="article-footer">
<blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接: </strong>
      <a href="https://xiaohei.im/hugo-theme-pure/collections/hashmap/" title="Collections-Hashmap" target="_blank" rel="external">https://xiaohei.im/hugo-theme-pure/collections/hashmap/</a>
    </li>
    <li class="post-copyright-license">
      <strong>License:</strong><a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN</a>
    </li>
  </ul>
</blockquote>

<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://github.com/xiaoheiAh" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://xiaohei.im/hugo-theme-pure/avatar.png" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://github.com/xiaoheiAh" target="_blank"><span class="text-dark">赵小黑</span><small class="ml-1x">Java Developer</small></a></h3>
        <div>好好学习~天天向上~</div>
      </div>
    </figure>
  </div>
</div>
    </div>
  </article>
<section id="comments">
</section>

</div><nav class="bar bar-footer clearfix" data-stick-bottom>
    <div class="bar-inner">
        <ul class="pager pull-left">
            <li class="prev">
                <a href="https://xiaohei.im/hugo-theme-pure/collections/hashset/" title="Collections-Hashset"><i
                        class="icon icon-angle-left"
                        aria-hidden="true"></i><span>&nbsp;&nbsp;下一篇</span></a>
            </li>
            <li class="next">
                <a href="https://xiaohei.im/hugo-theme-pure/collections/arraylist/"
                    title="Collections-Arraylist"><span>上一篇&nbsp;&nbsp;</span><i
                        class="icon icon-angle-right" aria-hidden="true"></i></a>
            </li>
            
            <li class="toggle-toc">
                <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false"
                    title="文章目录" role="button">
                    <span>[&nbsp;</span><span>文章目录</span>
                    <i class="text-collapsed icon icon-anchor"></i>
                    <i class="text-in icon icon-close"></i>
                    <span>]</span>
                </a>
            </li>
        </ul>
        
        <button type="button" class="btn btn-fancy btn-donate pop-onhover bg-gradient-warning" data-toggle="modal"
            data-target="#donateModal"><span>赏</span></button>
        
        <div class="bar-right">
            <div class="share-component" data-sites="weibo,qq,wechat,facebook,twitter"
                data-mobile-sites="weibo,qq,qzone"></div>
        </div>
    </div>
</nav>


<div class="modal modal-center modal-small modal-xs-full fade" id="donateModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content donate">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                    aria-hidden="true">&times;</span></button>
            <div class="modal-body">
                <div class="donate-box">
                    <div class="donate-head">
                        <p>感谢您的支持,我会继续努力的!</p>
                    </div>
                    <div class="tab-content">
                        <div role="tabpanel" class="tab-pane fade active in" id="alipay">
                            <div class="donate-payimg">
                                <img src="https://xiaohei.im/hugo-theme-pure/donate/alipayimg.png"
                                    alt="扫码支持" title="扫一扫" />
                            </div>
                            <p class="text-muted mv">扫码打赏, 多少你说了算~</p>
                            <p class="text-grey">打开支付宝扫一扫,即可进行扫码打赏哦~</p>
                        </div>
                        <div role="tabpanel" class="tab-pane fade" id="wechatpay">
                            <div class="donate-payimg">
                                <img src="https://xiaohei.im/hugo-theme-pure/donate/wechatpayimg.png"
                                    alt="扫码支持" title="扫一扫" />
                            </div>
                            <p class="text-muted mv">扫码打赏, 多少你说了算~</p>
                            <p class="text-grey">打开微信扫一扫,即可进行扫码打赏哦</p>
                        </div>
                    </div>
                    <div class="donate-footer">
                        <ul class="nav nav-tabs nav-justified" role="tablist">
                            <li role="presentation" class="active">
                                <a href="#alipay" id="alipay-tab" role="tab" data-toggle="tab" aria-controls="alipay"
                                    aria-expanded="true"><i class="icon icon-alipay"></i> 支付宝</a>
                            </li>
                            <li role="presentation" class="">
                                <a href="#wechatpay" role="tab" id="wechatpay-tab" data-toggle="tab"
                                    aria-controls="wechatpay" aria-expanded="false"><i class="icon icon-wepay"></i>
                                    微信支付</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</main><footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
<ul class="social-links">
    <li><a href="https://github.com/xiaoheiAh" target="_blank" title="github" data-toggle=tooltip data-placement=top >
            <i class="icon icon-github"></i></a></li>
    <li><a href="https://xiaohei.im/index.xml" target="_blank" title="rss" data-toggle=tooltip data-placement=top >
            <i class="icon icon-rss"></i></a></li>
</ul>
  <div class="copyright">
    &copy;2017  -
    2019
    <div class="publishby">
        Theme by <a href="https://github.com/xiaoheiAh" target="_blank"> xiaoheiAh </a>base on<a href="https://github.com/xiaoheiAh/hugo-theme-pure" target="_blank"> pure</a>.
    </div>
  </div>
</footer>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
<script>
    window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/highlight.min.js"></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/rust.min.js"></script>
<script type="text/javascript"
    src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/dockerfile.min.js"></script>
<script>
    hljs.configure({
        tabReplace: '    ', 
        classPrefix: ''     
        
    })
    hljs.initHighlightingOnLoad();
</script>
<script type="text/javascript" src="https://xiaohei.im/hugo-theme-pure/js/application.js"></script>
<script type="text/javascript" src="https://xiaohei.im/hugo-theme-pure/js/plugin.js"></script>
<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: '文章',
                PAGES: '页面',
                CATEGORIES: '分类',
                TAGS: '标签',
                UNTITLED: '(未命名)',
            },
            ROOT_URL: 'https:\/\/xiaohei.im\/hugo-theme-pure',
            CONTENT_URL: 'https:\/\/xiaohei.im\/hugo-theme-pure\/searchindex.json ',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>
<script type="text/javascript" src="https://xiaohei.im/hugo-theme-pure/js/insight.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.min.js"></script>
<script>
    tocbot.init({
        
        tocSelector: '.js-toc',
        
        contentSelector: '.js-toc-content',
        
        headingSelector: 'h1, h2, h3',
        
        hasInnerContainers: true,
    });
</script>

<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<script type="application/javascript">
var doNotTrack = false;
if (!doNotTrack) {
	window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
	ga('create', 'UA-98254666-1', 'auto');
	
	ga('send', 'pageview');
}
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>

  </body>
</html>