javamelody

JavaMelody : monitoring of JavaEE applications

image.png

weilibipei

违例匹配

“掷”出一个违例后,违例控制系统会按当初编写的顺序搜索“最接近”的控制器。一旦找到相符的控制器,就认为违例已得到控制,不再进行更多的搜索工作。

在违例和它的控制器之间,并不需要非常精确的匹配。一个衍生类对象可与基础类的一个控制器相配,如下例所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//: Human.java
// Catching Exception Hierarchies

class Annoyance extends Exception {}
class Sneeze extends Annoyance {}

public class Human {
public static void main(String[] args) {
try {
throw new Sneeze();
} catch(Sneeze s) {
System.out.println("Caught Sneeze");
} catch(Annoyance a) {
System.out.println("Caught Annoyance");
}
}
} ///:~

Sneeze违例会被相符的第一个catch从句捕获。当然,这只是第一个。然而,假如我们删除第一个catch从句:

1
2
3
4
5
try {
throw new Sneeze();
} catch(Annoyance a) {
System.out.println("Caught Annoyance");
}

那么剩下的catch从句依然能够工作,因为它捕获的是Sneeze的基础类。换言之,catch(Annoyance e)能捕获一个Annoyance以及从它衍生的任何类。这一点非常重要,因为一旦我们决定为一个方法添加更多的违例,而且它们都是从相同的基础类继承的,那么客户程序员的代码就不需要更改。至少能够假定它们捕获的是基础类。

若将基础类捕获从句置于第一位,试图“屏蔽”衍生类违例,就象下面这样:

1
2
3
4
5
6
7
try {
throw new Sneeze();
} catch(Annoyance a) {
System.out.println("Caught Annoyance");
} catch(Sneeze s) {
System.out.println("Caught Sneeze");
}

则编译器会产生一条出错消息,因为它发现永远不可能抵达Sneeze捕获从句。

9.8.1 违例准则

用违例做下面这些事情:

(1) 解决问题并再次调用造成违例的方法。

(2) 平息事态的发展,并在不重新尝试方法的前提下继续。

(3) 计算另一些结果,而不是希望方法产生的结果。

(4) 在当前环境中尽可能解决问题,以及将相同的违例重新“掷”出一个更高级的环境。

(5) 在当前环境中尽可能解决问题,以及将不同的违例重新“掷”出一个更高级的环境。

(6) 中止程序执行。

(7) 简化编码。若违例方案使事情变得更加复杂,那就会令人非常烦恼,不如不用。

(8) 使自己的库和程序变得更加安全。这既是一种“短期投资”(便于调试),也是一种“长期投资”(改善应用程序的健壮性)

Computer-network-books

网络安全从业者书单推荐

一、计算机及系统原理

《编码:隐匿在计算机软硬件背后的语言》

作者:(美国)Charles Petzold

《深入理解计算机系统》

作者:(美国)Randal E. Bryant

《深入解析windows操作系统》

作者:(美国)Mark E .Russinovich ,David A.Solomon

《Linux内核设计与实现》

作者:(美国)Robert Love

《深入理解android内核设计思想》

作者:林学森

《Android系统源代码情景分析》

作者:罗升阳

《深入解析Mac OS X & iOS操作系统》

作者:(美国)Jonathan Levin

《深入理解LINUX内核》

作者:(美国)Daniel P.Bovet

《代码揭秘:从C/C++的角度探秘计算机系统》

作者:左飞

《Android Dalvik虚拟机结构及机制剖析》(共2卷)

作者:吴艳霞,张国印

《最强Android书:架构大剖析》

作者:(美国)Jonathan Levin

二、编程开发

1、系统平台

(1)Windows

《Windows程序设计》

作者:(美国)Charles Petzold

《Windows核心编程》

作者:(美国)Jeffrey Richter

《Windows环境下32位汇编语言程序设计》

作者:罗云彬

《Windows驱动开发技术详解》

作者:张帆,史彩成

(2)Linux / Unix

《UNIX环境高级编程》

作者:(美国)W.Richard Stevens

《Linux程序设计》

作者:(美国)Nell Matthew,Richard Stones

《鸟哥的Linux私房菜》

作者:鸟哥(蔡德明)

《Linux设备驱动程序》

作者:(美国)Jonahan Corbet

(3)Mac OS X / iOS

《iOS编程》

作者:(美国)Joe Conway,Aaron Hillegass

《OS X与iOS内核编程》

作者:(澳大利亚)Ole Henry Halvorsen,Douglas Clarke

(4)Android

《第一行代码 Android》

作者:郭霖

《Android编程权威指南》

作者:(美国)Bill Phillips,Brian Hardy

2、编程语言

(1)C

《C程序设计语言》

作者:(美国)Brian W. Kernighan,Dennis M. Ritchie

《C Primer Plus》

作者:(美国)Stephen Prata

《C和指针》

作者:(美国)Kenneth A.Reek

《C陷阱与缺陷》

作者:(美国)Andrew Koenig

《C专家编程》

作者:(美国)Perter VanDer Linden

(2)C++

《C++ Primer Plus》

作者:(美国)Stephen Prata

《C++ Primer》

作者:(美国)Stanley B. Lippman,Josée LaJoie,Barbara E. Moo

(3)ASM

《Intel 汇编语言程序设计》

作者:(美国)Kip R.Irvine

《Intel 开发手册》

(4)JAVA

《JAVA核心技术》

作者:(美国)Cay S. Horstmann

《Java编程思想》

作者:(美国)Bruce Eckel

(5)JavaScript

《JavaScript DOM编程艺术》

作者:(英国)Jeremy Keith,(加拿大)Jeffrey Sambells

《JavaScript高级程序设计》

作者:(美国)Nicholas C.Zakas

(6)Python

《Python核心编程》

作者:(美国)Wesley Chun

(7)Shell

《Linux Shell脚本攻略》

作者:(印度)Sarath Lakshman

3、调试技术

《软件调试》

作者:张银奎

《Debug Hacks》

作者:(日本)吉冈弘隆,大和一洋,大岩尚宏,安部东洋,吉田俊辅

《格蠹汇编:软件调试案例集锦》

作者:张银奎

4、数据结构与算法

《数据结构与算法分析:C语言描述》

作者:(美国)Mark Allen Weiss

《算法导论》

作者:(美国)Thomas H.Cormen,Charles E.Leiserson,Ronald L.Rivest

5、编译原理

《编译系统透视:图解编译原理》

作者:新设计团队

《编译原理》

作者:(美国)Alfred V.Aho,Monica S.Lam,Ravi Sethi,Jeffrey D.Ullman

6、其他

《编程高手箴言》

作者:梁肇新

《代码整洁之道》

作者:(美国)Robert C.Martin

《代码大全》

作者:(美国)Steve McConnell

三、网络技术

《TCP/IP详解 卷1:协议》

作者:(美国)Kevin R. Fall,W.Richard Stevens

《Wireshark数据包分析实战》

作者:(美国)Chris Sanders

四、安全技术

1、安全开发

《天书夜读:从汇编语言到Windows内核编程》

作者:谭文,邵坚磊

《Rootkit:系统灰色地带的潜伏者》

作者:(美国)Bill Blunden

《Rootkits——Windows内核的安全防护》

作者:(美国)Greg Hoglund,James Butler

《BSD ROOTKIT 设计–内核黑客指引书》

作者:(美国)Joseph Kong

《寒江独钓:Windows内核安全编程》

作者:谭文,杨潇,邵坚磊

2、逆向工程

《加密与解密》

作者:段钢

《恶意软件分析诀窍与工具箱——对抗“流氓”软件的技术与利器》

作者:(美国)Michael.Hale.Ligh,Steven Adair

《C++反汇编与逆向分析技术揭秘》

作者:钱林松,赵海旭

《IDA Pro权威指南》

作者:(美国)Chris Eagle

《逆向工程权威指南》

作者:(乌克兰)Dennis Yurichev

《Android软件安全与逆向分析》

作者:丰生强

《macOS软件安全与逆向分析》

作者:丰生强、 邢俊杰

《iOS应用逆向工程(第2版)》

作者:沙梓社,吴航

3、Web安全

《黑客攻防技术宝典:Web实战篇》

作者:(美国)Dafydd Stuttard,Marcus Pinto

《白帽子讲Web安全》

作者:吴翰清

《Web安全测试》

作者:(美国)Paco Hope,Ben Waltller

《Web前端黑客技术揭秘》

作者:钟晨鸣,徐少培

《精通脚本黑客》

作者:曾云好

4、软件 / 系统安全

《0day安全:软件漏洞分析技术》

作者:王清

《漏洞战争:软件漏洞分析精要》

作者:林桠泉

《捉虫日记》

作者:(德国)Tobias Klein

《内核漏洞的利用与防范》

作者:(美国)Enrico Perla,Massimiliano Oldani

《Fuzzing for Software Security Testing and Quality Assurance(第二版)》

作者:(美国)Charlie Miller

《iOS Hacker’s Handbook》

作者:(美国)Charlie Miller

《The Mac Hacker’S Handbook》

作者:(美国)Charlie Miller

《Android安全攻防权威指南》

作者:(美国)Joshua J.Drake,(西班牙)Pau Oliva Fora,(美国)Collin Mulliner

《The Art of Software Security Assessment: Identifying and Preventing Software Vulnerabilities》

作者:(美国)Mark Dowd

《Android安全攻防实战》

作者:(美国)Keith Makan,Scott Alexander-Bown

《模糊测试:强制性安全漏洞发掘》

作者:(美国)Michael Sutton

《Exploit 编写系列教程》

作者:(美国)Corelan Team

《MacOS and iOS Internals, Volume III: Security & Insecurity》

作者:(美国)Jonathan Levin

《灰帽黑客(第4版):正义黑客的道德规范、渗透测试、攻击方法和漏洞分析技术》

作者:(美国)Allen Harper,Shon Harris

《威胁建模:设计和交付更安全的软件》

作者:(美国)Adam Shostack

5、无线电安全

《无线电安全攻防大揭秘》

作者:杨卿,黄琳

6、硬件安全

《硬件安全攻防大揭秘》

作者:简云定,杨卿

7、汽车安全

《智能汽车安全攻防大揭秘》

作者:李均,杨卿,曾颖涛,郑玉伟

《汽车黑客大曝光》

作者:(美国)Craig Smith

五、软技能

《软技能:代码之外的生存指南》

作者:(美国)John Sonmez

《程序员健康指南》

作者:(美国)Joe Kutner

《影响力》

作者:(美国)Robert B.Cialdini

《思考,快与慢》

作者:(美国)Daniel Kahneman

《写给大家看的设计书》

作者:(美国)Robin Williams

《听故事,学PPT设计》

作者:杨雪

《横向领导力》

作者:(美国)Roger Fisher,Alan Sharp

《职业情商》

作者:张新越

《程序员的成长课》

作者:安晓辉,周鹏

《高效演讲:斯坦福最受欢迎的沟通课》

作者:(美国)Peter Meyers,Shann Nix

《程序员的英语》

作者:(韩国)朴栽浒,李海永

《少有人走的路》

作者:(美国)斯科特·派克

《异类:不一样的成功启示录》

作者:(加拿大)马尔科姆·格拉德威尔

jna

Java Native Access - JNA

Build Status
Build status

Java Native Access (JNA)

The definitive JNA reference (including an overview and usage details) is in the JavaDoc. Please read the overview. Questions, comments, or exploratory conversations should begin on the mailing list, although you may find it easier to find answers to already-solved problems on StackOverflow.

JNA provides Java programs easy access to native shared libraries without writing anything but Java code - no JNI or native code is required. This functionality is comparable to Windows’ Platform/Invoke and Python’s ctypes.

JNA allows you to call directly into native functions using natural Java method invocation. The Java call looks just like the call does in native code. Most calls require no special handling or configuration; no boilerplate or generated code is required.

JNA uses a small JNI library stub to dynamically invoke native code. The developer uses a Java interface to describe functions and structures in the target native library. This makes it quite easy to take advantage of native platform features without incurring the high overhead of configuring and building JNI code for multiple platforms. Read this more in-depth description.

While significant attention has been paid to performance, correctness and ease of use take priority.

In addition, JNA includes a platform library with many native functions already mapped as well as a set of utility interfaces that simplify native access.

Projects Using JNA

JNA is a mature library with dozens of contributors and hundreds of commercial and non-commercial projects that use it. If you’re using JNA, feel free to tell us about it. Include some details about your company, project name, purpose and size and tell us how you use the library.

Interesting Investigations/Experiments

There are also a number of examples and projects within the contrib directory of the JNA project itself.

Supported Platforms

JNA will build on most linux-like platforms with a reasonable set of GNU tools and a JDK. See the native Makefile for native configurations that have been built and tested. If your platform is supported by libffi, then chances are you can build JNA for it.

Pre-built platform support may be found here.

Download

Version 5.4.0

JNA

Maven Central jna-5.4.0.jar

This is the core artifact of JNA and contains only the binding library and the
core helper classes.

JNA Platform

Maven Central jna-platform-5.4.0.jar

This artifact holds cross-platform mappings and mappings for a number of commonly used platform
functions, including a large number of Win32 mappings as well as a set of utility classes
that simplify native access. The code is tested and the utility interfaces ensure that
native memory management is taken care of correctly.

See PlatformLibrary.md for details.

Features

  • Automatic mapping from Java to native functions, with simple mappings for all primitive data types
  • Runs on most platforms which support Java
  • Automatic conversion between C and Java strings, with customizable encoding/decoding
  • Structure and Union arguments/return values, by reference and by value
  • Function Pointers, (callbacks from native code to Java) as arguments and/or members of a struct
  • Auto-generated Java proxies for native function pointers
  • By-reference (pointer-to-type) arguments
  • Java array and NIO Buffer arguments (primitive types and pointers) as pointer-to-buffer
  • Nested structures and arrays
  • Wide (wchar_t-based) strings
  • Native long support (32- or 64-bit as appropriate)
  • Demo applications/examples
  • Supported on 1.4 or later JVMs, including JavaME (earlier VMs may work with stubbed NIO support)
  • Customizable marshalling/unmarshalling (argument and return value conversions)
  • Customizable mapping from Java method to native function name, and customizable invocation to simulate C preprocessor function macros
  • Support for automatic Windows ASCII/UNICODE function mappings
  • Varargs support
  • Type-safety for native pointers
  • VM crash protection (optional)
  • Optimized direct mapping for high-performance applications.
  • COM support for early and late binding.
  • COM/Typelib java code generator.

Community and Support

All questions should be posted to the jna-users Google group. Issues can be submitted here on Github.

When posting to the mailing list, please include the following:

  • What OS/CPU/architecture you’re using (e.g. Windows 7 64-bit)
  • Reference to your native interface definitions (i.e. C headers), if available
  • The JNA mapping you’re trying to use
  • VM crash logs, if any
  • Example native usage, and your attempted Java usage

It’s nearly impossible to indicate proper Java usage when there’s no native
reference to work from.

For commercial support, please contact twalljava [at] java [dot] net.

Using the Library

Primary Documentation (JavaDoc)

The definitive JNA reference is in the JavaDoc.

Developers

Contributing

You’re encouraged to contribute to JNA. Fork the code from https://github.com/java-native-access/jna and submit pull requests.

For more information on setting up a development environment see Contributing to JNA.

If you are interested in paid support, feel free to say so on the jna-users mailing list. Most simple questions will be answered on the list, but more complicated work, new features or target platforms can be negotiated with any of the JNA developers (this is how several of JNA’s features came into being). You may even encounter other users with the same need and be able to cost share the new development.

License

This library is licensed under the LGPL, version 2.1 or later, and (from version 4.0 onward) the Apache Software License, version 2.0. Commercial license arrangements are negotiable.

NOTE: Oracle is not sponsoring this project, even though the package name (com.sun.jna) might imply otherwise.

LinkedList类

LinkedList类

image.png

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
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/

package java.util;

import java.util.function.Consumer;

/**
* Doubly-linked list implementation of the {@code List} and {@code Deque}
* interfaces. Implements all optional list operations, and permits all
* elements (including {@code null}).
*
* <p>All of the operations perform as could be expected for a doubly-linked
* list. Operations that index into the list will traverse the list from
* the beginning or the end, whichever is closer to the specified index.
*
* <p><strong>Note that this implementation is not synchronized.</strong>
* If multiple threads access a linked list concurrently, and at least
* one of the threads modifies the list structurally, it <i>must</i> be
* synchronized externally. (A structural modification is any operation
* that adds or deletes one or more elements; merely setting the value of
* an element is not a structural modification.) This is typically
* accomplished by synchronizing on some object that naturally
* encapsulates the list.
*
* If no such object exists, the list should be "wrapped" using the
* {@link Collections#synchronizedList Collections.synchronizedList}
* method. This is best done at creation time, to prevent accidental
* unsynchronized access to the list:<pre>
* List list = Collections.synchronizedList(new LinkedList(...));</pre>
*
* <p>The iterators returned by this class's {@code iterator} and
* {@code listIterator} methods are <i>fail-fast</i>: if the list is
* structurally modified at any time after the iterator is created, in
* any way except through the Iterator's own {@code remove} or
* {@code add} methods, the iterator will throw a {@link
* ConcurrentModificationException}. Thus, in the face of concurrent
* modification, the iterator fails quickly and cleanly, rather than
* risking arbitrary, non-deterministic behavior at an undetermined
* time in the future.
*
* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
* as it is, generally speaking, impossible to make any hard guarantees in the
* presence of unsynchronized concurrent modification. Fail-fast iterators
* throw {@code ConcurrentModificationException} on a best-effort basis.
* Therefore, it would be wrong to write a program that depended on this
* exception for its correctness: <i>the fail-fast behavior of iterators
* should be used only to detect bugs.</i>
*
* <p>This class is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @author Josh Bloch
* @see List
* @see ArrayList
* @since 1.2
* @param <E> the type of elements held in this collection
*/

public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
transient int size = 0;

/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first;

/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last;

/**
* Constructs an empty list.
*/
public LinkedList() {
}

/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}

/**
* Links e as first element.
*/
private void linkFirst(E e) {
final Node<E> f = first;
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
if (f == null)
last = newNode;
else
f.prev = newNode;
size++;
modCount++;
}

/**
* Links e as last element.
*/
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}

/**
* Inserts element e before non-null Node succ.
*/
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
final Node<E> pred = succ.prev;
final Node<E> newNode = new Node<>(pred, e, succ);
succ.prev = newNode;
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}

/**
* Unlinks non-null first node f.
*/
private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;
final E element = f.item;
final Node<E> next = f.next;
f.item = null;
f.next = null; // help GC
first = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}

/**
* Unlinks non-null last node l.
*/
private E unlinkLast(Node<E> l) {
// assert l == last && l != null;
final E element = l.item;
final Node<E> prev = l.prev;
l.item = null;
l.prev = null; // help GC
last = prev;
if (prev == null)
first = null;
else
prev.next = null;
size--;
modCount++;
return element;
}

/**
* Unlinks non-null node x.
*/
E unlink(Node<E> x) {
// assert x != null;
final E element = x.item;
final Node<E> next = x.next;
final Node<E> prev = x.prev;

if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}

if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}

x.item = null;
size--;
modCount++;
return element;
}

/**
* Returns the first element in this list.
*
* @return the first element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}

/**
* Returns the last element in this list.
*
* @return the last element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}

/**
* Removes and returns the first element from this list.
*
* @return the first element from this list
* @throws NoSuchElementException if this list is empty
*/
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}

/**
* Removes and returns the last element from this list.
*
* @return the last element from this list
* @throws NoSuchElementException if this list is empty
*/
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}

/**
* Inserts the specified element at the beginning of this list.
*
* @param e the element to add
*/
public void addFirst(E e) {
linkFirst(e);
}

/**
* Appends the specified element to the end of this list.
*
* <p>This method is equivalent to {@link #add}.
*
* @param e the element to add
*/
public void addLast(E e) {
linkLast(e);
}

/**
* Returns {@code true} if this list contains the specified element.
* More formally, returns {@code true} if and only if this list contains
* at least one element {@code e} such that
* <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
*
* @param o element whose presence in this list is to be tested
* @return {@code true} if this list contains the specified element
*/
public boolean contains(Object o) {
return indexOf(o) != -1;
}

/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list
*/
public int size() {
return size;
}

/**
* Appends the specified element to the end of this list.
*
* <p>This method is equivalent to {@link #addLast}.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
public boolean add(E e) {
linkLast(e);
return true;
}

/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If this list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* {@code i} such that
* <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
* (if such an element exists). Returns {@code true} if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return {@code true} if this list contained the specified element
*/
public boolean remove(Object o) {
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}

/**
* Appends all of the elements in the specified collection to the end of
* this list, in the order that they are returned by the specified
* collection's iterator. The behavior of this operation is undefined if
* the specified collection is modified while the operation is in
* progress. (Note that this will occur if the specified collection is
* this list, and it's nonempty.)
*
* @param c collection containing elements to be added to this list
* @return {@code true} if this list changed as a result of the call
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}

/**
* Inserts all of the elements in the specified collection into this
* list, starting at the specified position. Shifts the element
* currently at that position (if any) and any subsequent elements to
* the right (increases their indices). The new elements will appear
* in the list in the order that they are returned by the
* specified collection's iterator.
*
* @param index index at which to insert the first element
* from the specified collection
* @param c collection containing elements to be added to this list
* @return {@code true} if this list changed as a result of the call
* @throws IndexOutOfBoundsException {@inheritDoc}
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index);

Object[] a = c.toArray();
int numNew = a.length;
if (numNew == 0)
return false;

Node<E> pred, succ;
if (index == size) {
succ = null;
pred = last;
} else {
succ = node(index);
pred = succ.prev;
}

for (Object o : a) {
@SuppressWarnings("unchecked") E e = (E) o;
Node<E> newNode = new Node<>(pred, e, null);
if (pred == null)
first = newNode;
else
pred.next = newNode;
pred = newNode;
}

if (succ == null) {
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}

size += numNew;
modCount++;
return true;
}

/**
* Removes all of the elements from this list.
* The list will be empty after this call returns.
*/
public void clear() {
// Clearing all of the links between nodes is "unnecessary", but:
// - helps a generational GC if the discarded nodes inhabit
// more than one generation
// - is sure to free memory even if there is a reachable Iterator
for (Node<E> x = first; x != null; ) {
Node<E> next = x.next;
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0;
modCount++;
}


// Positional Access Operations

/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}

/**
* Replaces the element at the specified position in this list with the
* specified element.
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E set(int index, E element) {
checkElementIndex(index);
Node<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}

/**
* Inserts the specified element at the specified position in this list.
* Shifts the element currently at that position (if any) and any
* subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
checkPositionIndex(index);

if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}

/**
* Removes the element at the specified position in this list. Shifts any
* subsequent elements to the left (subtracts one from their indices).
* Returns the element that was removed from the list.
*
* @param index the index of the element to be removed
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}

/**
* Tells if the argument is the index of an existing element.
*/
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}

/**
* Tells if the argument is the index of a valid position for an
* iterator or an add operation.
*/
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}

/**
* Constructs an IndexOutOfBoundsException detail message.
* Of the many possible refactorings of the error handling code,
* this "outlining" performs best with both server and client VMs.
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}

private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

/**
* Returns the (non-null) Node at the specified element index.
*/
Node<E> node(int index) {
// assert isElementIndex(index);

if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}

// Search Operations

/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index {@code i} such that
* <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o element to search for
* @return the index of the first occurrence of the specified element in
* this list, or -1 if this list does not contain the element
*/
public int indexOf(Object o) {
int index = 0;
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}

/**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index {@code i} such that
* <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o element to search for
* @return the index of the last occurrence of the specified element in
* this list, or -1 if this list does not contain the element
*/
public int lastIndexOf(Object o) {
int index = size;
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (x.item == null)
return index;
}
} else {
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (o.equals(x.item))
return index;
}
}
return -1;
}

// Queue operations.

/**
* Retrieves, but does not remove, the head (first element) of this list.
*
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5
*/
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}

/**
* Retrieves, but does not remove, the head (first element) of this list.
*
* @return the head of this list
* @throws NoSuchElementException if this list is empty
* @since 1.5
*/
public E element() {
return getFirst();
}

/**
* Retrieves and removes the head (first element) of this list.
*
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5
*/
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}

/**
* Retrieves and removes the head (first element) of this list.
*
* @return the head of this list
* @throws NoSuchElementException if this list is empty
* @since 1.5
*/
public E remove() {
return removeFirst();
}

/**
* Adds the specified element as the tail (last element) of this list.
*
* @param e the element to add
* @return {@code true} (as specified by {@link Queue#offer})
* @since 1.5
*/
public boolean offer(E e) {
return add(e);
}

// Deque operations
/**
* Inserts the specified element at the front of this list.
*
* @param e the element to insert
* @return {@code true} (as specified by {@link Deque#offerFirst})
* @since 1.6
*/
public boolean offerFirst(E e) {
addFirst(e);
return true;
}

/**
* Inserts the specified element at the end of this list.
*
* @param e the element to insert
* @return {@code true} (as specified by {@link Deque#offerLast})
* @since 1.6
*/
public boolean offerLast(E e) {
addLast(e);
return true;
}

/**
* Retrieves, but does not remove, the first element of this list,
* or returns {@code null} if this list is empty.
*
* @return the first element of this list, or {@code null}
* if this list is empty
* @since 1.6
*/
public E peekFirst() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}

/**
* Retrieves, but does not remove, the last element of this list,
* or returns {@code null} if this list is empty.
*
* @return the last element of this list, or {@code null}
* if this list is empty
* @since 1.6
*/
public E peekLast() {
final Node<E> l = last;
return (l == null) ? null : l.item;
}

/**
* Retrieves and removes the first element of this list,
* or returns {@code null} if this list is empty.
*
* @return the first element of this list, or {@code null} if
* this list is empty
* @since 1.6
*/
public E pollFirst() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}

/**
* Retrieves and removes the last element of this list,
* or returns {@code null} if this list is empty.
*
* @return the last element of this list, or {@code null} if
* this list is empty
* @since 1.6
*/
public E pollLast() {
final Node<E> l = last;
return (l == null) ? null : unlinkLast(l);
}

/**
* Pushes an element onto the stack represented by this list. In other
* words, inserts the element at the front of this list.
*
* <p>This method is equivalent to {@link #addFirst}.
*
* @param e the element to push
* @since 1.6
*/
public void push(E e) {
addFirst(e);
}

/**
* Pops an element from the stack represented by this list. In other
* words, removes and returns the first element of this list.
*
* <p>This method is equivalent to {@link #removeFirst()}.
*
* @return the element at the front of this list (which is the top
* of the stack represented by this list)
* @throws NoSuchElementException if this list is empty
* @since 1.6
*/
public E pop() {
return removeFirst();
}

/**
* Removes the first occurrence of the specified element in this
* list (when traversing the list from head to tail). If the list
* does not contain the element, it is unchanged.
*
* @param o element to be removed from this list, if present
* @return {@code true} if the list contained the specified element
* @since 1.6
*/
public boolean removeFirstOccurrence(Object o) {
return remove(o);
}

/**
* Removes the last occurrence of the specified element in this
* list (when traversing the list from head to tail). If the list
* does not contain the element, it is unchanged.
*
* @param o element to be removed from this list, if present
* @return {@code true} if the list contained the specified element
* @since 1.6
*/
public boolean removeLastOccurrence(Object o) {
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = last; x != null; x = x.prev) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}

/**
* Returns a list-iterator of the elements in this list (in proper
* sequence), starting at the specified position in the list.
* Obeys the general contract of {@code List.listIterator(int)}.<p>
*
* The list-iterator is <i>fail-fast</i>: if the list is structurally
* modified at any time after the Iterator is created, in any way except
* through the list-iterator's own {@code remove} or {@code add}
* methods, the list-iterator will throw a
* {@code ConcurrentModificationException}. Thus, in the face of
* concurrent modification, the iterator fails quickly and cleanly, rather
* than risking arbitrary, non-deterministic behavior at an undetermined
* time in the future.
*
* @param index index of the first element to be returned from the
* list-iterator (by a call to {@code next})
* @return a ListIterator of the elements in this list (in proper
* sequence), starting at the specified position in the list
* @throws IndexOutOfBoundsException {@inheritDoc}
* @see List#listIterator(int)
*/
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}

private class ListItr implements ListIterator<E> {
private Node<E> lastReturned;
private Node<E> next;
private int nextIndex;
private int expectedModCount = modCount;

ListItr(int index) {
// assert isPositionIndex(index);
next = (index == size) ? null : node(index);
nextIndex = index;
}

public boolean hasNext() {
return nextIndex < size;
}

public E next() {
checkForComodification();
if (!hasNext())
throw new NoSuchElementException();

lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.item;
}

public boolean hasPrevious() {
return nextIndex > 0;
}

public E previous() {
checkForComodification();
if (!hasPrevious())
throw new NoSuchElementException();

lastReturned = next = (next == null) ? last : next.prev;
nextIndex--;
return lastReturned.item;
}

public int nextIndex() {
return nextIndex;
}

public int previousIndex() {
return nextIndex - 1;
}

public void remove() {
checkForComodification();
if (lastReturned == null)
throw new IllegalStateException();

Node<E> lastNext = lastReturned.next;
unlink(lastReturned);
if (next == lastReturned)
next = lastNext;
else
nextIndex--;
lastReturned = null;
expectedModCount++;
}

public void set(E e) {
if (lastReturned == null)
throw new IllegalStateException();
checkForComodification();
lastReturned.item = e;
}

public void add(E e) {
checkForComodification();
lastReturned = null;
if (next == null)
linkLast(e);
else
linkBefore(e, next);
nextIndex++;
expectedModCount++;
}

public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (modCount == expectedModCount && nextIndex < size) {
action.accept(next.item);
lastReturned = next;
next = next.next;
nextIndex++;
}
checkForComodification();
}

final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}

private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;

Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}

/**
* @since 1.6
*/
public Iterator<E> descendingIterator() {
return new DescendingIterator();
}

/**
* Adapter to provide descending iterators via ListItr.previous
*/
private class DescendingIterator implements Iterator<E> {
private final ListItr itr = new ListItr(size());
public boolean hasNext() {
return itr.hasPrevious();
}
public E next() {
return itr.previous();
}
public void remove() {
itr.remove();
}
}

@SuppressWarnings("unchecked")
private LinkedList<E> superClone() {
try {
return (LinkedList<E>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}

/**
* Returns a shallow copy of this {@code LinkedList}. (The elements
* themselves are not cloned.)
*
* @return a shallow copy of this {@code LinkedList} instance
*/
public Object clone() {
LinkedList<E> clone = superClone();

// Put clone into "virgin" state
clone.first = clone.last = null;
clone.size = 0;
clone.modCount = 0;

// Initialize clone with our elements
for (Node<E> x = first; x != null; x = x.next)
clone.add(x.item);

return clone;
}

/**
* Returns an array containing all of the elements in this list
* in proper sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this list
* in proper sequence
*/
public Object[] toArray() {
Object[] result = new Object[size];
int i = 0;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
return result;
}

/**
* Returns an array containing all of the elements in this list in
* proper sequence (from first to last element); the runtime type of
* the returned array is that of the specified array. If the list fits
* in the specified array, it is returned therein. Otherwise, a new
* array is allocated with the runtime type of the specified array and
* the size of this list.
*
* <p>If the list fits in the specified array with room to spare (i.e.,
* the array has more elements than the list), the element in the array
* immediately following the end of the list is set to {@code null}.
* (This is useful in determining the length of the list <i>only</i> if
* the caller knows that the list does not contain any null elements.)
*
* <p>Like the {@link #toArray()} method, this method acts as bridge between
* array-based and collection-based APIs. Further, this method allows
* precise control over the runtime type of the output array, and may,
* under certain circumstances, be used to save allocation costs.
*
* <p>Suppose {@code x} is a list known to contain only strings.
* The following code can be used to dump the list into a newly
* allocated array of {@code String}:
*
* <pre>
* String[] y = x.toArray(new String[0]);</pre>
*
* Note that {@code toArray(new Object[0])} is identical in function to
* {@code toArray()}.
*
* @param a the array into which the elements of the list are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose.
* @return an array containing the elements of the list
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this list
* @throws NullPointerException if the specified array is null
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
a = (T[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size);
int i = 0;
Object[] result = a;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;

if (a.length > size)
a[size] = null;

return a;
}

private static final long serialVersionUID = 876323262645176354L;

/**
* Saves the state of this {@code LinkedList} instance to a stream
* (that is, serializes it).
*
* @serialData The size of the list (the number of elements it
* contains) is emitted (int), followed by all of its
* elements (each an Object) in the proper order.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out any hidden serialization magic
s.defaultWriteObject();

// Write out size
s.writeInt(size);

// Write out all elements in the proper order.
for (Node<E> x = first; x != null; x = x.next)
s.writeObject(x.item);
}

/**
* Reconstitutes this {@code LinkedList} instance from a stream
* (that is, deserializes it).
*/
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in any hidden serialization magic
s.defaultReadObject();

// Read in size
int size = s.readInt();

// Read in all elements in the proper order.
for (int i = 0; i < size; i++)
linkLast((E)s.readObject());
}

/**
* Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
* and <em>fail-fast</em> {@link Spliterator} over the elements in this
* list.
*
* <p>The {@code Spliterator} reports {@link Spliterator#SIZED} and
* {@link Spliterator#ORDERED}. Overriding implementations should document
* the reporting of additional characteristic values.
*
* @implNote
* The {@code Spliterator} additionally reports {@link Spliterator#SUBSIZED}
* and implements {@code trySplit} to permit limited parallelism..
*
* @return a {@code Spliterator} over the elements in this list
* @since 1.8
*/
@Override
public Spliterator<E> spliterator() {
return new LLSpliterator<E>(this, -1, 0);
}

/** A customized variant of Spliterators.IteratorSpliterator */
static final class LLSpliterator<E> implements Spliterator<E> {
static final int BATCH_UNIT = 1 << 10; // batch array size increment
static final int MAX_BATCH = 1 << 25; // max batch array size;
final LinkedList<E> list; // null OK unless traversed
Node<E> current; // current node; null until initialized
int est; // size estimate; -1 until first needed
int expectedModCount; // initialized when est set
int batch; // batch size for splits

LLSpliterator(LinkedList<E> list, int est, int expectedModCount) {
this.list = list;
this.est = est;
this.expectedModCount = expectedModCount;
}

final int getEst() {
int s; // force initialization
final LinkedList<E> lst;
if ((s = est) < 0) {
if ((lst = list) == null)
s = est = 0;
else {
expectedModCount = lst.modCount;
current = lst.first;
s = est = lst.size;
}
}
return s;
}

public long estimateSize() { return (long) getEst(); }

public Spliterator<E> trySplit() {
Node<E> p;
int s = getEst();
if (s > 1 && (p = current) != null) {
int n = batch + BATCH_UNIT;
if (n > s)
n = s;
if (n > MAX_BATCH)
n = MAX_BATCH;
Object[] a = new Object[n];
int j = 0;
do { a[j++] = p.item; } while ((p = p.next) != null && j < n);
current = p;
batch = j;
est = s - j;
return Spliterators.spliterator(a, 0, j, Spliterator.ORDERED);
}
return null;
}

public void forEachRemaining(Consumer<? super E> action) {
Node<E> p; int n;
if (action == null) throw new NullPointerException();
if ((n = getEst()) > 0 && (p = current) != null) {
current = null;
est = 0;
do {
E e = p.item;
p = p.next;
action.accept(e);
} while (p != null && --n > 0);
}
if (list.modCount != expectedModCount)
throw new ConcurrentModificationException();
}

public boolean tryAdvance(Consumer<? super E> action) {
Node<E> p;
if (action == null) throw new NullPointerException();
if (getEst() > 0 && (p = current) != null) {
--est;
E e = p.item;
current = p.next;
action.accept(e);
if (list.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
return false;
}

public int characteristics() {
return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
}
}

}

HashMap类

HashMap类

image.png

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
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
/*
* Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/

package java.util;

import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import sun.misc.SharedSecrets;

/**
* Hash table based implementation of the <tt>Map</tt> interface. This
* implementation provides all of the optional map operations, and permits
* <tt>null</tt> values and the <tt>null</tt> key. (The <tt>HashMap</tt>
* class is roughly equivalent to <tt>Hashtable</tt>, except that it is
* unsynchronized and permits nulls.) This class makes no guarantees as to
* the order of the map; in particular, it does not guarantee that the order
* will remain constant over time.
*
* <p>This implementation provides constant-time performance for the basic
* operations (<tt>get</tt> and <tt>put</tt>), assuming the hash function
* disperses the elements properly among the buckets. Iteration over
* collection views requires time proportional to the "capacity" of the
* <tt>HashMap</tt> instance (the number of buckets) plus its size (the number
* of key-value mappings). Thus, it's very important not to set the initial
* capacity too high (or the load factor too low) if iteration performance is
* important.
*
* <p>An instance of <tt>HashMap</tt> has two parameters that affect its
* performance: <i>initial capacity</i> and <i>load factor</i>. The
* <i>capacity</i> is the number of buckets in the hash table, and the initial
* capacity is simply the capacity at the time the hash table is created. The
* <i>load factor</i> is a measure of how full the hash table is allowed to
* get before its capacity is automatically increased. When the number of
* entries in the hash table exceeds the product of the load factor and the
* current capacity, the hash table is <i>rehashed</i> (that is, internal data
* structures are rebuilt) so that the hash table has approximately twice the
* number of buckets.
*
* <p>As a general rule, the default load factor (.75) offers a good
* tradeoff between time and space costs. Higher values decrease the
* space overhead but increase the lookup cost (reflected in most of
* the operations of the <tt>HashMap</tt> class, including
* <tt>get</tt> and <tt>put</tt>). The expected number of entries in
* the map and its load factor should be taken into account when
* setting its initial capacity, so as to minimize the number of
* rehash operations. If the initial capacity is greater than the
* maximum number of entries divided by the load factor, no rehash
* operations will ever occur.
*
* <p>If many mappings are to be stored in a <tt>HashMap</tt>
* instance, creating it with a sufficiently large capacity will allow
* the mappings to be stored more efficiently than letting it perform
* automatic rehashing as needed to grow the table. Note that using
* many keys with the same {@code hashCode()} is a sure way to slow
* down performance of any hash table. To ameliorate impact, when keys
* are {@link Comparable}, this class may use comparison order among
* keys to help break ties.
*
* <p><strong>Note that this implementation is not synchronized.</strong>
* If multiple threads access a hash map concurrently, and at least one of
* the threads modifies the map structurally, it <i>must</i> be
* synchronized externally. (A structural modification is any operation
* that adds or deletes one or more mappings; merely changing the value
* associated with a key that an instance already contains is not a
* structural modification.) This is typically accomplished by
* synchronizing on some object that naturally encapsulates the map.
*
* If no such object exists, the map should be "wrapped" using the
* {@link Collections#synchronizedMap Collections.synchronizedMap}
* method. This is best done at creation time, to prevent accidental
* unsynchronized access to the map:<pre>
* Map m = Collections.synchronizedMap(new HashMap(...));</pre>
*
* <p>The iterators returned by all of this class's "collection view methods"
* are <i>fail-fast</i>: if the map is structurally modified at any time after
* the iterator is created, in any way except through the iterator's own
* <tt>remove</tt> method, the iterator will throw a
* {@link ConcurrentModificationException}. Thus, in the face of concurrent
* modification, the iterator fails quickly and cleanly, rather than risking
* arbitrary, non-deterministic behavior at an undetermined time in the
* future.
*
* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
* as it is, generally speaking, impossible to make any hard guarantees in the
* presence of unsynchronized concurrent modification. Fail-fast iterators
* throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
* Therefore, it would be wrong to write a program that depended on this
* exception for its correctness: <i>the fail-fast behavior of iterators
* should be used only to detect bugs.</i>
*
* <p>This class is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @param <K> the type of keys maintained by this map
* @param <V> the type of mapped values
*
* @author Doug Lea
* @author Josh Bloch
* @author Arthur van Hoff
* @author Neal Gafter
* @see Object#hashCode()
* @see Collection
* @see Map
* @see TreeMap
* @see Hashtable
* @since 1.2
*/
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {

private static final long serialVersionUID = 362498820763181265L;

/*
* Implementation notes.
*
* This map usually acts as a binned (bucketed) hash table, but
* when bins get too large, they are transformed into bins of
* TreeNodes, each structured similarly to those in
* java.util.TreeMap. Most methods try to use normal bins, but
* relay to TreeNode methods when applicable (simply by checking
* instanceof a node). Bins of TreeNodes may be traversed and
* used like any others, but additionally support faster lookup
* when overpopulated. However, since the vast majority of bins in
* normal use are not overpopulated, checking for existence of
* tree bins may be delayed in the course of table methods.
*
* Tree bins (i.e., bins whose elements are all TreeNodes) are
* ordered primarily by hashCode, but in the case of ties, if two
* elements are of the same "class C implements Comparable<C>",
* type then their compareTo method is used for ordering. (We
* conservatively check generic types via reflection to validate
* this -- see method comparableClassFor). The added complexity
* of tree bins is worthwhile in providing worst-case O(log n)
* operations when keys either have distinct hashes or are
* orderable, Thus, performance degrades gracefully under
* accidental or malicious usages in which hashCode() methods
* return values that are poorly distributed, as well as those in
* which many keys share a hashCode, so long as they are also
* Comparable. (If neither of these apply, we may waste about a
* factor of two in time and space compared to taking no
* precautions. But the only known cases stem from poor user
* programming practices that are already so slow that this makes
* little difference.)
*
* Because TreeNodes are about twice the size of regular nodes, we
* use them only when bins contain enough nodes to warrant use
* (see TREEIFY_THRESHOLD). And when they become too small (due to
* removal or resizing) they are converted back to plain bins. In
* usages with well-distributed user hashCodes, tree bins are
* rarely used. Ideally, under random hashCodes, the frequency of
* nodes in bins follows a Poisson distribution
* (http://en.wikipedia.org/wiki/Poisson_distribution) with a
* parameter of about 0.5 on average for the default resizing
* threshold of 0.75, although with a large variance because of
* resizing granularity. Ignoring variance, the expected
* occurrences of list size k are (exp(-0.5) * pow(0.5, k) /
* factorial(k)). The first values are:
*
* 0: 0.60653066
* 1: 0.30326533
* 2: 0.07581633
* 3: 0.01263606
* 4: 0.00157952
* 5: 0.00015795
* 6: 0.00001316
* 7: 0.00000094
* 8: 0.00000006
* more: less than 1 in ten million
*
* The root of a tree bin is normally its first node. However,
* sometimes (currently only upon Iterator.remove), the root might
* be elsewhere, but can be recovered following parent links
* (method TreeNode.root()).
*
* All applicable internal methods accept a hash code as an
* argument (as normally supplied from a public method), allowing
* them to call each other without recomputing user hashCodes.
* Most internal methods also accept a "tab" argument, that is
* normally the current table, but may be a new or old one when
* resizing or converting.
*
* When bin lists are treeified, split, or untreeified, we keep
* them in the same relative access/traversal order (i.e., field
* Node.next) to better preserve locality, and to slightly
* simplify handling of splits and traversals that invoke
* iterator.remove. When using comparators on insertion, to keep a
* total ordering (or as close as is required here) across
* rebalancings, we compare classes and identityHashCodes as
* tie-breakers.
*
* The use and transitions among plain vs tree modes is
* complicated by the existence of subclass LinkedHashMap. See
* below for hook methods defined to be invoked upon insertion,
* removal and access that allow LinkedHashMap internals to
* otherwise remain independent of these mechanics. (This also
* requires that a map instance be passed to some utility methods
* that may create new nodes.)
*
* The concurrent-programming-like SSA-based coding style helps
* avoid aliasing errors amid all of the twisty pointer operations.
*/

/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 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 <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 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;

/**
* 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;

/**
* 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;

/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;

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 K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + 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<?,?> 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);
}

/**
* Returns x's Class if it is of the form "class C implements
* Comparable<C>", 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 <tt>HashMap</tt> 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 <tt>HashMap</tt> 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 <tt>HashMap</tt> 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 <tt>HashMap</tt> with the same mappings as the
* specified <tt>Map</tt>. The <tt>HashMap</tt> is created with
* default load factor (0.75) and an initial capacity sufficient to
* hold the mappings in the specified <tt>Map</tt>.
*
* @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 <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> 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.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>
* 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 <tt>true</tt> if this map contains a mapping for the
* specified key.
*
* @param key The key whose presence in this map is to be tested
* @return <tt>true</tt> 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 <tt>key</tt>, 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 <tt>key</tt>, 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 <tt>true</tt> 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 <tt>true</tt> 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 <tt>remove</tt> operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
* operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
* operations.
*
* @return a set view of the keys contained in this map
*/
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}

final class KeySet extends AbstractSet<K> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<K> 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<K> 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 <tt>remove</tt> operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the <tt>Iterator.remove</tt>,
* <tt>Collection.remove</tt>, <tt>removeAll</tt>,
* <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
* support the <tt>add</tt> or <tt>addAll</tt> operations.
*
* @return a view of the values contained in this map
*/
public Collection<V> values() {
Collection<V> vs = values;
if (vs == null) {
vs = new Values();
values = vs;
}
return vs;
}

final class Values extends AbstractCollection<V> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<V> iterator() { return new ValueIterator(); }
public final boolean contains(Object o) { return containsValue(o); }
public final Spliterator<V> 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 <tt>remove</tt> operation, or through the
* <tt>setValue</tt> 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 <tt>Iterator.remove</tt>,
* <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
* <tt>clear</tt> operations. It does not support the
* <tt>add</tt> or <tt>addAll</tt> 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 <tt>HashMap</tt> 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 <tt>HashMap</tt> instance to a stream (i.e.,
* serialize it).
*
* @serialData The <i>capacity</i> 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<K> {
public final K next() { return nextNode().key; }
}

final class ValueIterator extends HashIterator
implements Iterator<V> {
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<K> {
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<V> {
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 = 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;
}
}

/* ------------------------------------------------------------ */
// LinkedHashMap support


/*
* The following package-protected methods are designed to be
* overridden by LinkedHashMap, but not by any other subclass.
* Nearly all other internal methods are also package-protected
* but are declared final, so can be used by LinkedHashMap, view
* classes, and HashSet.
*/

// Create a regular (non-tree) node
Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
return new Node<>(hash, key, value, next);
}

// For conversion from TreeNodes to plain nodes
Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) {
return new Node<>(p.hash, p.key, p.value, next);
}

// Create a tree bin node
TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) {
return new TreeNode<>(hash, key, value, next);
}

// For treeifyBin
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
return new TreeNode<>(p.hash, p.key, p.value, next);
}

/**
* Reset to initial default state. Called by clone and readObject.
*/
void reinitialize() {
table = null;
entrySet = null;
keySet = null;
values = null;
modCount = 0;
threshold = 0;
size = 0;
}

// Callbacks to allow LinkedHashMap post-actions
void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }

// Called only from writeObject, to ensure compatible ordering.
void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException {
Node<K,V>[] tab;
if (size > 0 && (tab = table) != null) {
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
s.writeObject(e.key);
s.writeObject(e.value);
}
}
}
}

/* ------------------------------------------------------------ */
// Tree bins

/**
* Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
* extends Node) so can be used as extension of either regular or
* linked node.
*/
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}

/**
* Returns root of tree containing this node.
*/
final TreeNode<K,V> root() {
for (TreeNode<K,V> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}

/**
* Ensures that the given root is the first node of its bin.
*/
static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
int n;
if (root != null && tab != null && (n = tab.length) > 0) {
int index = (n - 1) & root.hash;
TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
if (root != first) {
Node<K,V> rn;
tab[index] = root;
TreeNode<K,V> rp = root.prev;
if ((rn = root.next) != null)
((TreeNode<K,V>)rn).prev = rp;
if (rp != null)
rp.next = rn;
if (first != null)
first.prev = root;
root.next = first;
root.prev = null;
}
assert checkInvariants(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<K,V> find(int h, Object k, Class<?> kc) {
TreeNode<K,V> p = this;
do {
int ph, dir; K pk;
TreeNode<K,V> pl = p.left, pr = p.right, q;
if ((ph = p.hash) > h)
p = pl;
else if (ph < h)
p = pr;
else if ((pk = p.key) == k || (k != null && 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) &&
(dir = compareComparables(kc, k, pk)) != 0)
p = (dir < 0) ? pl : pr;
else if ((q = pr.find(h, k, kc)) != null)
return q;
else
p = pl;
} while (p != null);
return null;
}

/**
* Calls find for root node.
*/
final TreeNode<K,V> getTreeNode(int h, Object k) {
return ((parent != null) ? root() : this).find(h, k, null);
}

/**
* Tie-breaking utility for ordering insertions when equal
* hashCodes and non-comparable. We don't require a total
* order, just a consistent insertion rule to maintain
* equivalence across rebalancings. Tie-breaking further than
* necessary simplifies testing a bit.
*/
static int tieBreakOrder(Object a, Object b) {
int d;
if (a == null || b == null ||
(d = a.getClass().getName().
compareTo(b.getClass().getName())) == 0)
d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
-1 : 1);
return d;
}

/**
* Forms tree of the nodes linked from this node.
* @return root of tree
*/
final void treeify(Node<K,V>[] tab) {
TreeNode<K,V> root = null;
for (TreeNode<K,V> x = this, next; x != null; x = next) {
next = (TreeNode<K,V>)x.next;
x.left = x.right = null;
if (root == null) {
x.parent = null;
x.red = false;
root = x;
}
else {
K k = x.key;
int h = x.hash;
Class<?> kc = null;
for (TreeNode<K,V> p = root;;) {
int dir, ph;
K pk = p.key;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
dir = tieBreakOrder(k, pk);

TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
x.parent = xp;
if (dir <= 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<K,V> untreeify(HashMap<K,V> map) {
Node<K,V> hd = null, tl = null;
for (Node<K,V> q = this; q != null; q = q.next) {
Node<K,V> p = map.replacementNode(q, null);
if (tl == null)
hd = p;
else
tl.next = p;
tl = p;
}
return hd;
}

/**
* Tree version of putVal.
*/
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
TreeNode<K,V> root = (parent != null) ? root() : this;
for (TreeNode<K,V> p = root;;) {
int dir, ph; K pk;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
if (!searched) {
TreeNode<K,V> q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.find(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.find(h, k, kc)) != null))
return q;
}
dir = tieBreakOrder(k, pk);
}

TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
Node<K,V> xpn = xp.next;
TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
if (dir <= 0)
xp.left = x;
else
xp.right = x;
xp.next = x;
x.parent = x.prev = xp;
if (xpn != null)
((TreeNode<K,V>)xpn).prev = x;
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}

/**
* Removes the given node, that must be present before this call.
* This is messier than typical red-black deletion code because we
* cannot swap the contents of an interior node with a leaf
* successor that is pinned by "next" pointers that are accessible
* independently during traversal. So instead we swap the tree
* linkages. If the current tree appears to have too few nodes,
* the bin is converted back to a plain bin. (The test triggers
* somewhere between 2 and 6 nodes, depending on tree structure).
*/
final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
boolean movable) {
int n;
if (tab == null || (n = tab.length) == 0)
return;
int index = (n - 1) & hash;
TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;
if (pred == null)
tab[index] = first = succ;
else
pred.next = succ;
if (succ != null)
succ.prev = pred;
if (first == null)
return;
if (root.parent != null)
root = root.root();
if (root == null || root.right == null ||
(rl = root.left) == null || rl.left == null) {
tab[index] = first.untreeify(map); // too small
return;
}
TreeNode<K,V> p = this, pl = left, pr = right, replacement;
if (pl != null && pr != null) {
TreeNode<K,V> s = pr, sl;
while ((sl = s.left) != null) // find successor
s = sl;
boolean c = s.red; s.red = p.red; p.red = c; // swap colors
TreeNode<K,V> sr = s.right;
TreeNode<K,V> pp = p.parent;
if (s == pr) { // p was s's direct parent
p.parent = s;
s.right = p;
}
else {
TreeNode<K,V> sp = s.parent;
if ((p.parent = sp) != null) {
if (s == sp.left)
sp.left = p;
else
sp.right = p;
}
if ((s.right = pr) != null)
pr.parent = s;
}
p.left = null;
if ((p.right = sr) != null)
sr.parent = p;
if ((s.left = pl) != null)
pl.parent = s;
if ((s.parent = pp) == null)
root = s;
else if (p == pp.left)
pp.left = s;
else
pp.right = s;
if (sr != null)
replacement = sr;
else
replacement = p;
}
else if (pl != null)
replacement = pl;
else if (pr != null)
replacement = pr;
else
replacement = p;
if (replacement != p) {
TreeNode<K,V> pp = replacement.parent = p.parent;
if (pp == null)
root = replacement;
else if (p == pp.left)
pp.left = replacement;
else
pp.right = replacement;
p.left = p.right = p.parent = null;
}

TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);

if (replacement == p) { // detach
TreeNode<K,V> pp = p.parent;
p.parent = null;
if (pp != null) {
if (p == pp.left)
pp.left = null;
else if (p == pp.right)
pp.right = null;
}
}
if (movable)
moveRootToFront(tab, r);
}

/**
* Splits nodes in a tree bin into lower and upper tree bins,
* or untreeifies if now too small. Called only from resize;
* see above discussion about split bits and indices.
*
* @param map the map
* @param tab the table for recording bin heads
* @param index the index of the table being split
* @param bit the bit of hash to split on
*/
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
TreeNode<K,V> b = this;
// Relink into lo and hi lists, preserving order
TreeNode<K,V> loHead = null, loTail = null;
TreeNode<K,V> hiHead = null, hiTail = null;
int lc = 0, hc = 0;
for (TreeNode<K,V> e = b, next; e != null; e = next) {
next = (TreeNode<K,V>)e.next;
e.next = null;
if ((e.hash & bit) == 0) {
if ((e.prev = loTail) == null)
loHead = e;
else
loTail.next = e;
loTail = e;
++lc;
}
else {
if ((e.prev = hiTail) == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
++hc;
}
}

if (loHead != null) {
if (lc <= UNTREEIFY_THRESHOLD)
tab[index] = loHead.untreeify(map);
else {
tab[index] = loHead;
if (hiHead != null) // (else is already treeified)
loHead.treeify(tab);
}
}
if (hiHead != null) {
if (hc <= UNTREEIFY_THRESHOLD)
tab[index + bit] = hiHead.untreeify(map);
else {
tab[index + bit] = hiHead;
if (loHead != null)
hiHead.treeify(tab);
}
}
}

/* ------------------------------------------------------------ */
// Red-black tree methods, all adapted from CLR

static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
TreeNode<K,V> p) {
TreeNode<K,V> r, pp, rl;
if (p != null && (r = p.right) != null) {
if ((rl = p.right = r.left) != null)
rl.parent = p;
if ((pp = r.parent = p.parent) == null)
(root = r).red = false;
else if (pp.left == p)
pp.left = r;
else
pp.right = r;
r.left = p;
p.parent = r;
}
return root;
}

static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
TreeNode<K,V> p) {
TreeNode<K,V> l, pp, lr;
if (p != null && (l = p.left) != null) {
if ((lr = p.left = l.right) != null)
lr.parent = p;
if ((pp = l.parent = p.parent) == null)
(root = l).red = false;
else if (pp.right == p)
pp.right = l;
else
pp.left = l;
l.right = p;
p.parent = l;
}
return root;
}

static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
TreeNode<K,V> x) {
x.red = true;
for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
if ((xp = x.parent) == null) {
x.red = false;
return x;
}
else if (!xp.red || (xpp = xp.parent) == null)
return root;
if (xp == (xppl = xpp.left)) {
if ((xppr = xpp.right) != null && xppr.red) {
xppr.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.right) {
root = rotateLeft(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateRight(root, xpp);
}
}
}
}
else {
if (xppl != null && xppl.red) {
xppl.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.left) {
root = rotateRight(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateLeft(root, xpp);
}
}
}
}
}
}

static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
TreeNode<K,V> x) {
for (TreeNode<K,V> xp, xpl, xpr;;) {
if (x == null || x == root)
return root;
else if ((xp = x.parent) == null) {
x.red = false;
return x;
}
else if (x.red) {
x.red = false;
return root;
}
else if ((xpl = xp.left) == x) {
if ((xpr = xp.right) != null && xpr.red) {
xpr.red = false;
xp.red = true;
root = rotateLeft(root, xp);
xpr = (xp = x.parent) == null ? null : xp.right;
}
if (xpr == null)
x = xp;
else {
TreeNode<K,V> sl = xpr.left, sr = xpr.right;
if ((sr == null || !sr.red) &&
(sl == null || !sl.red)) {
xpr.red = true;
x = xp;
}
else {
if (sr == null || !sr.red) {
if (sl != null)
sl.red = false;
xpr.red = true;
root = rotateRight(root, xpr);
xpr = (xp = x.parent) == null ?
null : xp.right;
}
if (xpr != null) {
xpr.red = (xp == null) ? false : xp.red;
if ((sr = xpr.right) != null)
sr.red = false;
}
if (xp != null) {
xp.red = false;
root = rotateLeft(root, xp);
}
x = root;
}
}
}
else { // symmetric
if (xpl != null && xpl.red) {
xpl.red = false;
xp.red = true;
root = rotateRight(root, xp);
xpl = (xp = x.parent) == null ? null : xp.left;
}
if (xpl == null)
x = xp;
else {
TreeNode<K,V> sl = xpl.left, sr = xpl.right;
if ((sl == null || !sl.red) &&
(sr == null || !sr.red)) {
xpl.red = true;
x = xp;
}
else {
if (sl == null || !sl.red) {
if (sr != null)
sr.red = false;
xpl.red = true;
root = rotateLeft(root, xpl);
xpl = (xp = x.parent) == null ?
null : xp.left;
}
if (xpl != null) {
xpl.red = (xp == null) ? false : xp.red;
if ((sl = xpl.left) != null)
sl.red = false;
}
if (xp != null) {
xp.red = false;
root = rotateRight(root, xp);
}
x = root;
}
}
}
}
}

/**
* Recursive invariant check
*/
static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
tb = t.prev, tn = (TreeNode<K,V>)t.next;
if (tb != null && tb.next != t)
return false;
if (tn != null && tn.prev != t)
return false;
if (tp != null && t != tp.left && t != tp.right)
return false;
if (tl != null && (tl.parent != t || tl.hash > t.hash))
return false;
if (tr != null && (tr.parent != t || tr.hash < t.hash))
return false;
if (t.red && tl != null && tl.red && tr != null && tr.red)
return false;
if (tl != null && !checkInvariants(tl))
return false;
if (tr != null && !checkInvariants(tr))
return false;
return true;
}
}

}

BigInteger类

BigInteger类

image.png

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
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package java.math;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.io.StreamCorruptedException;
import java.io.ObjectInputStream.GetField;
import java.io.ObjectOutputStream.PutField;
import java.util.Arrays;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import jdk.internal.HotSpotIntrinsicCandidate;
import jdk.internal.misc.Unsafe;

public class BigInteger extends Number implements Comparable<BigInteger> {
final int signum;
final int[] mag;
private int bitCountPlusOne;
private int bitLengthPlusOne;
private int lowestSetBitPlusTwo;
private int firstNonzeroIntNumPlusTwo;
static final long LONG_MASK = 4294967295L;
private static final int MAX_MAG_LENGTH = 67108864;
private static final int PRIME_SEARCH_BIT_LENGTH_LIMIT = 500000000;
private static final int KARATSUBA_THRESHOLD = 80;
private static final int TOOM_COOK_THRESHOLD = 240;
private static final int KARATSUBA_SQUARE_THRESHOLD = 128;
private static final int TOOM_COOK_SQUARE_THRESHOLD = 216;
static final int BURNIKEL_ZIEGLER_THRESHOLD = 80;
static final int BURNIKEL_ZIEGLER_OFFSET = 40;
private static final int SCHOENHAGE_BASE_CONVERSION_THRESHOLD = 20;
private static final int MULTIPLY_SQUARE_THRESHOLD = 20;
private static final int MONTGOMERY_INTRINSIC_THRESHOLD = 512;
private static long[] bitsPerDigit = new long[]{0L, 0L, 1024L, 1624L, 2048L, 2378L, 2648L, 2875L, 3072L, 3247L, 3402L, 3543L, 3672L, 3790L, 3899L, 4001L, 4096L, 4186L, 4271L, 4350L, 4426L, 4498L, 4567L, 4633L, 4696L, 4756L, 4814L, 4870L, 4923L, 4975L, 5025L, 5074L, 5120L, 5166L, 5210L, 5253L, 5295L};
private static final int SMALL_PRIME_THRESHOLD = 95;
private static final int DEFAULT_PRIME_CERTAINTY = 100;
private static final BigInteger SMALL_PRIME_PRODUCT = valueOf(152125131763605L);
private static final int MAX_CONSTANT = 16;
private static BigInteger[] posConst = new BigInteger[17];
private static BigInteger[] negConst = new BigInteger[17];
private static volatile BigInteger[][] powerCache;
private static final double[] logCache;
private static final double LOG_TWO = Math.log(2.0D);
public static final BigInteger ZERO;
public static final BigInteger ONE;
public static final BigInteger TWO;
private static final BigInteger NEGATIVE_ONE;
public static final BigInteger TEN;
static int[] bnExpModThreshTable;
private static String[] zeros;
private static int[] digitsPerLong;
private static BigInteger[] longRadix;
private static int[] digitsPerInt;
private static int[] intRadix;
private static final long serialVersionUID = -8287574255936472291L;
private static final ObjectStreamField[] serialPersistentFields;

public BigInteger(byte[] val, int off, int len) {
if (val.length == 0) {
throw new NumberFormatException("Zero length BigInteger");
} else {
Objects.checkFromIndexSize(off, len, val.length);
if (val[off] < 0) {
this.mag = makePositive(val, off, len);
this.signum = -1;
} else {
this.mag = stripLeadingZeroBytes(val, off, len);
this.signum = this.mag.length == 0 ? 0 : 1;
}

if (this.mag.length >= 67108864) {
this.checkRange();
}

}
}

public BigInteger(byte[] val) {
this((byte[])val, 0, val.length);
}

private BigInteger(int[] val) {
if (val.length == 0) {
throw new NumberFormatException("Zero length BigInteger");
} else {
if (val[0] < 0) {
this.mag = makePositive(val);
this.signum = -1;
} else {
this.mag = trustedStripLeadingZeroInts(val);
this.signum = this.mag.length == 0 ? 0 : 1;
}

if (this.mag.length >= 67108864) {
this.checkRange();
}

}
}

public BigInteger(int signum, byte[] magnitude, int off, int len) {
if (signum >= -1 && signum <= 1) {
Objects.checkFromIndexSize(off, len, magnitude.length);
this.mag = stripLeadingZeroBytes(magnitude, off, len);
if (this.mag.length == 0) {
this.signum = 0;
} else {
if (signum == 0) {
throw new NumberFormatException("signum-magnitude mismatch");
}

this.signum = signum;
}

if (this.mag.length >= 67108864) {
this.checkRange();
}

} else {
throw new NumberFormatException("Invalid signum value");
}
}

public BigInteger(int signum, byte[] magnitude) {
this(signum, magnitude, 0, magnitude.length);
}

private BigInteger(int signum, int[] magnitude) {
this.mag = stripLeadingZeroInts(magnitude);
if (signum >= -1 && signum <= 1) {
if (this.mag.length == 0) {
this.signum = 0;
} else {
if (signum == 0) {
throw new NumberFormatException("signum-magnitude mismatch");
}

this.signum = signum;
}

if (this.mag.length >= 67108864) {
this.checkRange();
}

} else {
throw new NumberFormatException("Invalid signum value");
}
}

public BigInteger(String val, int radix) {
int cursor = 0;
int len = val.length();
if (radix >= 2 && radix <= 36) {
if (len == 0) {
throw new NumberFormatException("Zero length BigInteger");
} else {
int sign = 1;
int index1 = val.lastIndexOf(45);
int index2 = val.lastIndexOf(43);
if (index1 >= 0) {
if (index1 != 0 || index2 >= 0) {
throw new NumberFormatException("Illegal embedded sign character");
}

sign = -1;
cursor = 1;
} else if (index2 >= 0) {
if (index2 != 0) {
throw new NumberFormatException("Illegal embedded sign character");
}

cursor = 1;
}

if (cursor == len) {
throw new NumberFormatException("Zero length BigInteger");
} else {
while(cursor < len && Character.digit(val.charAt(cursor), radix) == 0) {
++cursor;
}

if (cursor == len) {
this.signum = 0;
this.mag = ZERO.mag;
} else {
int numDigits = len - cursor;
this.signum = sign;
long numBits = ((long)numDigits * bitsPerDigit[radix] >>> 10) + 1L;
if (numBits + 31L >= 4294967296L) {
reportOverflow();
}

int numWords = (int)(numBits + 31L) >>> 5;
int[] magnitude = new int[numWords];
int firstGroupLen = numDigits % digitsPerInt[radix];
if (firstGroupLen == 0) {
firstGroupLen = digitsPerInt[radix];
}

String group = val.substring(cursor, cursor += firstGroupLen);
magnitude[numWords - 1] = Integer.parseInt(group, radix);
if (magnitude[numWords - 1] < 0) {
throw new NumberFormatException("Illegal digit");
} else {
int superRadix = intRadix[radix];
boolean var16 = false;

while(cursor < len) {
group = val.substring(cursor, cursor += digitsPerInt[radix]);
int groupVal = Integer.parseInt(group, radix);
if (groupVal < 0) {
throw new NumberFormatException("Illegal digit");
}

destructiveMulAdd(magnitude, superRadix, groupVal);
}

this.mag = trustedStripLeadingZeroInts(magnitude);
if (this.mag.length >= 67108864) {
this.checkRange();
}

}
}
}
}
} else {
throw new NumberFormatException("Radix out of range");
}
}

BigInteger(char[] val, int sign, int len) {
int cursor;
for(cursor = 0; cursor < len && Character.digit(val[cursor], 10) == 0; ++cursor) {
}

if (cursor == len) {
this.signum = 0;
this.mag = ZERO.mag;
} else {
int numDigits = len - cursor;
this.signum = sign;
int numWords;
if (len < 10) {
numWords = 1;
} else {
long numBits = ((long)numDigits * bitsPerDigit[10] >>> 10) + 1L;
if (numBits + 31L >= 4294967296L) {
reportOverflow();
}

numWords = (int)(numBits + 31L) >>> 5;
}

int[] magnitude = new int[numWords];
int firstGroupLen = numDigits % digitsPerInt[10];
if (firstGroupLen == 0) {
firstGroupLen = digitsPerInt[10];
}

magnitude[numWords - 1] = this.parseInt(val, cursor, cursor += firstGroupLen);

while(cursor < len) {
int groupVal = this.parseInt(val, cursor, cursor += digitsPerInt[10]);
destructiveMulAdd(magnitude, intRadix[10], groupVal);
}

this.mag = trustedStripLeadingZeroInts(magnitude);
if (this.mag.length >= 67108864) {
this.checkRange();
}

}
}

private int parseInt(char[] source, int start, int end) {
int result = Character.digit(source[start++], 10);
if (result == -1) {
throw new NumberFormatException(new String(source));
} else {
for(int index = start; index < end; ++index) {
int nextVal = Character.digit(source[index], 10);
if (nextVal == -1) {
throw new NumberFormatException(new String(source));
}

result = 10 * result + nextVal;
}

return result;
}
}

private static void destructiveMulAdd(int[] x, int y, int z) {
long ylong = (long)y & 4294967295L;
long zlong = (long)z & 4294967295L;
int len = x.length;
long product = 0L;
long carry = 0L;

for(int i = len - 1; i >= 0; --i) {
product = ylong * ((long)x[i] & 4294967295L) + carry;
x[i] = (int)product;
carry = product >>> 32;
}

long sum = ((long)x[len - 1] & 4294967295L) + zlong;
x[len - 1] = (int)sum;
carry = sum >>> 32;

for(int i = len - 2; i >= 0; --i) {
sum = ((long)x[i] & 4294967295L) + carry;
x[i] = (int)sum;
carry = sum >>> 32;
}

}

public BigInteger(String val) {
this((String)val, 10);
}

public BigInteger(int numBits, Random rnd) {
this(1, (byte[])randomBits(numBits, rnd));
}

private static byte[] randomBits(int numBits, Random rnd) {
if (numBits < 0) {
throw new IllegalArgumentException("numBits must be non-negative");
} else {
int numBytes = (int)(((long)numBits + 7L) / 8L);
byte[] randomBits = new byte[numBytes];
if (numBytes > 0) {
rnd.nextBytes(randomBits);
int excessBits = 8 * numBytes - numBits;
randomBits[0] = (byte)(randomBits[0] & (1 << 8 - excessBits) - 1);
}

return randomBits;
}
}

public BigInteger(int bitLength, int certainty, Random rnd) {
if (bitLength < 2) {
throw new ArithmeticException("bitLength < 2");
} else {
BigInteger prime = bitLength < 95 ? smallPrime(bitLength, certainty, rnd) : largePrime(bitLength, certainty, rnd);
this.signum = 1;
this.mag = prime.mag;
}
}

public static BigInteger probablePrime(int bitLength, Random rnd) {
if (bitLength < 2) {
throw new ArithmeticException("bitLength < 2");
} else {
return bitLength < 95 ? smallPrime(bitLength, 100, rnd) : largePrime(bitLength, 100, rnd);
}
}

private static BigInteger smallPrime(int bitLength, int certainty, Random rnd) {
int magLen = bitLength + 31 >>> 5;
int[] temp = new int[magLen];
int highBit = 1 << (bitLength + 31 & 31);
int highMask = (highBit << 1) - 1;

BigInteger p;
do {
long r;
do {
for(int i = 0; i < magLen; ++i) {
temp[i] = rnd.nextInt();
}

temp[0] = temp[0] & highMask | highBit;
if (bitLength > 2) {
temp[magLen - 1] |= 1;
}

p = new BigInteger(temp, 1);
if (bitLength <= 6) {
break;
}

r = p.remainder(SMALL_PRIME_PRODUCT).longValue();
} while(r % 3L == 0L || r % 5L == 0L || r % 7L == 0L || r % 11L == 0L || r % 13L == 0L || r % 17L == 0L || r % 19L == 0L || r % 23L == 0L || r % 29L == 0L || r % 31L == 0L || r % 37L == 0L || r % 41L == 0L);

if (bitLength < 4) {
return p;
}
} while(!p.primeToCertainty(certainty, rnd));

return p;
}

private static BigInteger largePrime(int bitLength, int certainty, Random rnd) {
BigInteger p = (new BigInteger(bitLength, rnd)).setBit(bitLength - 1);
int[] var10000 = p.mag;
int var10001 = p.mag.length - 1;
var10000[var10001] &= -2;
int searchLen = getPrimeSearchLen(bitLength);
BitSieve searchSieve = new BitSieve(p, searchLen);

BigInteger candidate;
for(candidate = searchSieve.retrieve(p, certainty, rnd); candidate == null || candidate.bitLength() != bitLength; candidate = searchSieve.retrieve(p, certainty, rnd)) {
p = p.add(valueOf((long)(2 * searchLen)));
if (p.bitLength() != bitLength) {
p = (new BigInteger(bitLength, rnd)).setBit(bitLength - 1);
}

var10000 = p.mag;
var10001 = p.mag.length - 1;
var10000[var10001] &= -2;
searchSieve = new BitSieve(p, searchLen);
}

return candidate;
}

public BigInteger nextProbablePrime() {
if (this.signum < 0) {
throw new ArithmeticException("start < 0: " + this);
} else if (this.signum != 0 && !this.equals(ONE)) {
BigInteger result = this.add(ONE);
if (result.bitLength() < 95) {
if (!result.testBit(0)) {
result = result.add(ONE);
}

while(true) {
while(true) {
if (result.bitLength() > 6) {
long r = result.remainder(SMALL_PRIME_PRODUCT).longValue();
if (r % 3L == 0L || r % 5L == 0L || r % 7L == 0L || r % 11L == 0L || r % 13L == 0L || r % 17L == 0L || r % 19L == 0L || r % 23L == 0L || r % 29L == 0L || r % 31L == 0L || r % 37L == 0L || r % 41L == 0L) {
result = result.add(TWO);
continue;
}
}

if (result.bitLength() < 4) {
return result;
}

if (result.primeToCertainty(100, (Random)null)) {
return result;
}

result = result.add(TWO);
}
}
} else {
if (result.testBit(0)) {
result = result.subtract(ONE);
}

int searchLen = getPrimeSearchLen(result.bitLength());

while(true) {
BitSieve searchSieve = new BitSieve(result, searchLen);
BigInteger candidate = searchSieve.retrieve(result, 100, (Random)null);
if (candidate != null) {
return candidate;
}

result = result.add(valueOf((long)(2 * searchLen)));
}
}
} else {
return TWO;
}
}

private static int getPrimeSearchLen(int bitLength) {
if (bitLength > 500000001) {
throw new ArithmeticException("Prime search implementation restriction on bitLength");
} else {
return bitLength / 20 * 64;
}
}

boolean primeToCertainty(int certainty, Random random) {
int rounds = false;
int n = (Math.min(certainty, 2147483646) + 1) / 2;
int sizeInBits = this.bitLength();
byte rounds;
int rounds;
if (sizeInBits < 100) {
rounds = 50;
rounds = n < rounds ? n : rounds;
return this.passesMillerRabin(rounds, random);
} else {
if (sizeInBits < 256) {
rounds = 27;
} else if (sizeInBits < 512) {
rounds = 15;
} else if (sizeInBits < 768) {
rounds = 8;
} else if (sizeInBits < 1024) {
rounds = 4;
} else {
rounds = 2;
}

rounds = n < rounds ? n : rounds;
return this.passesMillerRabin(rounds, random) && this.passesLucasLehmer();
}
}

private boolean passesLucasLehmer() {
BigInteger thisPlusOne = this.add(ONE);

int d;
for(d = 5; jacobiSymbol(d, this) != -1; d = d < 0 ? Math.abs(d) + 2 : -(d + 2)) {
}

BigInteger u = lucasLehmerSequence(d, thisPlusOne, this);
return u.mod(this).equals(ZERO);
}

private static int jacobiSymbol(int p, BigInteger n) {
if (p == 0) {
return 0;
} else {
int j = 1;
int u = n.mag[n.mag.length - 1];
int t;
if (p < 0) {
p = -p;
t = u & 7;
if (t == 3 || t == 7) {
j = -j;
}
}

while((p & 3) == 0) {
p >>= 2;
}

if ((p & 1) == 0) {
p >>= 1;
if (((u ^ u >> 1) & 2) != 0) {
j = -j;
}
}

if (p == 1) {
return j;
} else {
if ((p & u & 2) != 0) {
j = -j;
}

for(u = n.mod(valueOf((long)p)).intValue(); u != 0; u %= t) {
while((u & 3) == 0) {
u >>= 2;
}

if ((u & 1) == 0) {
u >>= 1;
if (((p ^ p >> 1) & 2) != 0) {
j = -j;
}
}

if (u == 1) {
return j;
}

assert u < p;

t = u;
u = p;
p = t;
if ((u & t & 2) != 0) {
j = -j;
}
}

return 0;
}
}
}

private static BigInteger lucasLehmerSequence(int z, BigInteger k, BigInteger n) {
BigInteger d = valueOf((long)z);
BigInteger u = ONE;
BigInteger v = ONE;

for(int i = k.bitLength() - 2; i >= 0; --i) {
BigInteger u2 = u.multiply(v).mod(n);
BigInteger v2 = v.square().add(d.multiply(u.square())).mod(n);
if (v2.testBit(0)) {
v2 = v2.subtract(n);
}

v2 = v2.shiftRight(1);
u = u2;
v = v2;
if (k.testBit(i)) {
u2 = u2.add(v2).mod(n);
if (u2.testBit(0)) {
u2 = u2.subtract(n);
}

u2 = u2.shiftRight(1);
v2 = v2.add(d.multiply(u)).mod(n);
if (v2.testBit(0)) {
v2 = v2.subtract(n);
}

v2 = v2.shiftRight(1);
u = u2;
v = v2;
}
}

return u;
}

private boolean passesMillerRabin(int iterations, Random rnd) {
BigInteger thisMinusOne = this.subtract(ONE);
int a = thisMinusOne.getLowestSetBit();
BigInteger m = thisMinusOne.shiftRight(a);
if (rnd == null) {
rnd = ThreadLocalRandom.current();
}

for(int i = 0; i < iterations; ++i) {
BigInteger b;
do {
do {
b = new BigInteger(this.bitLength(), (Random)rnd);
} while(b.compareTo(ONE) <= 0);
} while(b.compareTo(this) >= 0);

int j = 0;

for(BigInteger z = b.modPow(m, this); (j != 0 || !z.equals(ONE)) && !z.equals(thisMinusOne); z = z.modPow(TWO, this)) {
if (j > 0 && z.equals(ONE)) {
return false;
}

++j;
if (j == a) {
return false;
}
}
}

return true;
}

BigInteger(int[] magnitude, int signum) {
this.signum = magnitude.length == 0 ? 0 : signum;
this.mag = magnitude;
if (this.mag.length >= 67108864) {
this.checkRange();
}

}

private BigInteger(byte[] magnitude, int signum) {
this.signum = magnitude.length == 0 ? 0 : signum;
this.mag = stripLeadingZeroBytes(magnitude, 0, magnitude.length);
if (this.mag.length >= 67108864) {
this.checkRange();
}

}

private void checkRange() {
if (this.mag.length > 67108864 || this.mag.length == 67108864 && this.mag[0] < 0) {
reportOverflow();
}

}

private static void reportOverflow() {
throw new ArithmeticException("BigInteger would overflow supported range");
}

public static BigInteger valueOf(long val) {
if (val == 0L) {
return ZERO;
} else if (val > 0L && val <= 16L) {
return posConst[(int)val];
} else {
return val < 0L && val >= -16L ? negConst[(int)(-val)] : new BigInteger(val);
}
}

private BigInteger(long val) {
if (val < 0L) {
val = -val;
this.signum = -1;
} else {
this.signum = 1;
}

int highWord = (int)(val >>> 32);
if (highWord == 0) {
this.mag = new int[1];
this.mag[0] = (int)val;
} else {
this.mag = new int[2];
this.mag[0] = highWord;
this.mag[1] = (int)val;
}

}

private static BigInteger valueOf(int[] val) {
return val[0] > 0 ? new BigInteger(val, 1) : new BigInteger(val);
}

public BigInteger add(BigInteger val) {
if (val.signum == 0) {
return this;
} else if (this.signum == 0) {
return val;
} else if (val.signum == this.signum) {
return new BigInteger(add(this.mag, val.mag), this.signum);
} else {
int cmp = this.compareMagnitude(val);
if (cmp == 0) {
return ZERO;
} else {
int[] resultMag = cmp > 0 ? subtract(this.mag, val.mag) : subtract(val.mag, this.mag);
resultMag = trustedStripLeadingZeroInts(resultMag);
return new BigInteger(resultMag, cmp == this.signum ? 1 : -1);
}
}
}

BigInteger add(long val) {
if (val == 0L) {
return this;
} else if (this.signum == 0) {
return valueOf(val);
} else if (Long.signum(val) == this.signum) {
return new BigInteger(add(this.mag, Math.abs(val)), this.signum);
} else {
int cmp = this.compareMagnitude(val);
if (cmp == 0) {
return ZERO;
} else {
int[] resultMag = cmp > 0 ? subtract(this.mag, Math.abs(val)) : subtract(Math.abs(val), this.mag);
resultMag = trustedStripLeadingZeroInts(resultMag);
return new BigInteger(resultMag, cmp == this.signum ? 1 : -1);
}
}
}

private static int[] add(int[] x, long val) {
long sum = 0L;
int xIndex = x.length;
int highWord = (int)(val >>> 32);
int[] result;
if (highWord == 0) {
result = new int[xIndex];
--xIndex;
sum = ((long)x[xIndex] & 4294967295L) + val;
result[xIndex] = (int)sum;
} else {
if (xIndex == 1) {
result = new int[2];
sum = val + ((long)x[0] & 4294967295L);
result[1] = (int)sum;
result[0] = (int)(sum >>> 32);
return result;
}

result = new int[xIndex];
--xIndex;
sum = ((long)x[xIndex] & 4294967295L) + (val & 4294967295L);
result[xIndex] = (int)sum;
--xIndex;
sum = ((long)x[xIndex] & 4294967295L) + ((long)highWord & 4294967295L) + (sum >>> 32);
result[xIndex] = (int)sum;
}

boolean carry;
for(carry = sum >>> 32 != 0L; xIndex > 0 && carry; carry = (result[xIndex] = x[xIndex] + 1) == 0) {
--xIndex;
}

while(xIndex > 0) {
--xIndex;
result[xIndex] = x[xIndex];
}

if (carry) {
int[] bigger = new int[result.length + 1];
System.arraycopy(result, 0, bigger, 1, result.length);
bigger[0] = 1;
return bigger;
} else {
return result;
}
}

private static int[] add(int[] x, int[] y) {
if (x.length < y.length) {
int[] tmp = x;
x = y;
y = tmp;
}

int xIndex = x.length;
int yIndex = y.length;
int[] result = new int[xIndex];
long sum = 0L;
if (yIndex == 1) {
--xIndex;
sum = ((long)x[xIndex] & 4294967295L) + ((long)y[0] & 4294967295L);
result[xIndex] = (int)sum;
} else {
while(yIndex > 0) {
--xIndex;
long var10000 = (long)x[xIndex] & 4294967295L;
--yIndex;
sum = var10000 + ((long)y[yIndex] & 4294967295L) + (sum >>> 32);
result[xIndex] = (int)sum;
}
}

boolean carry;
for(carry = sum >>> 32 != 0L; xIndex > 0 && carry; carry = (result[xIndex] = x[xIndex] + 1) == 0) {
--xIndex;
}

while(xIndex > 0) {
--xIndex;
result[xIndex] = x[xIndex];
}

if (carry) {
int[] bigger = new int[result.length + 1];
System.arraycopy(result, 0, bigger, 1, result.length);
bigger[0] = 1;
return bigger;
} else {
return result;
}
}

private static int[] subtract(long val, int[] little) {
int highWord = (int)(val >>> 32);
int[] result;
if (highWord == 0) {
result = new int[]{(int)(val - ((long)little[0] & 4294967295L))};
return result;
} else {
result = new int[2];
long difference;
if (little.length == 1) {
difference = ((long)((int)val) & 4294967295L) - ((long)little[0] & 4294967295L);
result[1] = (int)difference;
boolean borrow = difference >> 32 != 0L;
if (borrow) {
result[0] = highWord - 1;
} else {
result[0] = highWord;
}

return result;
} else {
difference = ((long)((int)val) & 4294967295L) - ((long)little[1] & 4294967295L);
result[1] = (int)difference;
difference = ((long)highWord & 4294967295L) - ((long)little[0] & 4294967295L) + (difference >> 32);
result[0] = (int)difference;
return result;
}
}
}

private static int[] subtract(int[] big, long val) {
int highWord = (int)(val >>> 32);
int bigIndex = big.length;
int[] result = new int[bigIndex];
long difference = 0L;
if (highWord == 0) {
--bigIndex;
difference = ((long)big[bigIndex] & 4294967295L) - val;
result[bigIndex] = (int)difference;
} else {
--bigIndex;
difference = ((long)big[bigIndex] & 4294967295L) - (val & 4294967295L);
result[bigIndex] = (int)difference;
--bigIndex;
difference = ((long)big[bigIndex] & 4294967295L) - ((long)highWord & 4294967295L) + (difference >> 32);
result[bigIndex] = (int)difference;
}

for(boolean borrow = difference >> 32 != 0L; bigIndex > 0 && borrow; borrow = (result[bigIndex] = big[bigIndex] - 1) == -1) {
--bigIndex;
}

while(bigIndex > 0) {
--bigIndex;
result[bigIndex] = big[bigIndex];
}

return result;
}

public BigInteger subtract(BigInteger val) {
if (val.signum == 0) {
return this;
} else if (this.signum == 0) {
return val.negate();
} else if (val.signum != this.signum) {
return new BigInteger(add(this.mag, val.mag), this.signum);
} else {
int cmp = this.compareMagnitude(val);
if (cmp == 0) {
return ZERO;
} else {
int[] resultMag = cmp > 0 ? subtract(this.mag, val.mag) : subtract(val.mag, this.mag);
resultMag = trustedStripLeadingZeroInts(resultMag);
return new BigInteger(resultMag, cmp == this.signum ? 1 : -1);
}
}
}

private static int[] subtract(int[] big, int[] little) {
int bigIndex = big.length;
int[] result = new int[bigIndex];
int littleIndex = little.length;

long difference;
for(difference = 0L; littleIndex > 0; result[bigIndex] = (int)difference) {
--bigIndex;
long var10000 = (long)big[bigIndex] & 4294967295L;
--littleIndex;
difference = var10000 - ((long)little[littleIndex] & 4294967295L) + (difference >> 32);
}

for(boolean borrow = difference >> 32 != 0L; bigIndex > 0 && borrow; borrow = (result[bigIndex] = big[bigIndex] - 1) == -1) {
--bigIndex;
}

while(bigIndex > 0) {
--bigIndex;
result[bigIndex] = big[bigIndex];
}

return result;
}

public BigInteger multiply(BigInteger val) {
return this.multiply(val, false);
}

private BigInteger multiply(BigInteger val, boolean isRecursion) {
if (val.signum != 0 && this.signum != 0) {
int xlen = this.mag.length;
if (val == this && xlen > 20) {
return this.square();
} else {
int ylen = val.mag.length;
if (xlen >= 80 && ylen >= 80) {
if (xlen < 240 && ylen < 240) {
return multiplyKaratsuba(this, val);
} else {
if (!isRecursion && (long)(bitLength(this.mag, this.mag.length) + bitLength(val.mag, val.mag.length)) > 2147483648L) {
reportOverflow();
}

return multiplyToomCook3(this, val);
}
} else {
int resultSign = this.signum == val.signum ? 1 : -1;
if (val.mag.length == 1) {
return multiplyByInt(this.mag, val.mag[0], resultSign);
} else if (this.mag.length == 1) {
return multiplyByInt(val.mag, this.mag[0], resultSign);
} else {
int[] result = multiplyToLen(this.mag, xlen, val.mag, ylen, (int[])null);
result = trustedStripLeadingZeroInts(result);
return new BigInteger(result, resultSign);
}
}
}
} else {
return ZERO;
}
}

private static BigInteger multiplyByInt(int[] x, int y, int sign) {
if (Integer.bitCount(y) == 1) {
return new BigInteger(shiftLeft(x, Integer.numberOfTrailingZeros(y)), sign);
} else {
int xlen = x.length;
int[] rmag = new int[xlen + 1];
long carry = 0L;
long yl = (long)y & 4294967295L;
int rstart = rmag.length - 1;

for(int i = xlen - 1; i >= 0; --i) {
long product = ((long)x[i] & 4294967295L) * yl + carry;
rmag[rstart--] = (int)product;
carry = product >>> 32;
}

if (carry == 0L) {
rmag = Arrays.copyOfRange(rmag, 1, rmag.length);
} else {
rmag[rstart] = (int)carry;
}

return new BigInteger(rmag, sign);
}
}

BigInteger multiply(long v) {
if (v != 0L && this.signum != 0) {
if (v == -9223372036854775808L) {
return this.multiply(valueOf(v));
} else {
int rsign = v > 0L ? this.signum : -this.signum;
if (v < 0L) {
v = -v;
}

long dh = v >>> 32;
long dl = v & 4294967295L;
int xlen = this.mag.length;
int[] value = this.mag;
int[] rmag = dh == 0L ? new int[xlen + 1] : new int[xlen + 2];
long carry = 0L;
int rstart = rmag.length - 1;

int i;
long product;
for(i = xlen - 1; i >= 0; --i) {
product = ((long)value[i] & 4294967295L) * dl + carry;
rmag[rstart--] = (int)product;
carry = product >>> 32;
}

rmag[rstart] = (int)carry;
if (dh != 0L) {
carry = 0L;
rstart = rmag.length - 2;

for(i = xlen - 1; i >= 0; --i) {
product = ((long)value[i] & 4294967295L) * dh + ((long)rmag[rstart] & 4294967295L) + carry;
rmag[rstart--] = (int)product;
carry = product >>> 32;
}

rmag[0] = (int)carry;
}

if (carry == 0L) {
rmag = Arrays.copyOfRange(rmag, 1, rmag.length);
}

return new BigInteger(rmag, rsign);
}
} else {
return ZERO;
}
}

private static int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {
multiplyToLenCheck(x, xlen);
multiplyToLenCheck(y, ylen);
return implMultiplyToLen(x, xlen, y, ylen, z);
}

@HotSpotIntrinsicCandidate
private static int[] implMultiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {
int xstart = xlen - 1;
int ystart = ylen - 1;
if (z == null || z.length < xlen + ylen) {
z = new int[xlen + ylen];
}

long carry = 0L;
int i = ystart;

int j;
for(j = ystart + 1 + xstart; i >= 0; --j) {
long product = ((long)y[i] & 4294967295L) * ((long)x[xstart] & 4294967295L) + carry;
z[j] = (int)product;
carry = product >>> 32;
--i;
}

z[xstart] = (int)carry;

for(i = xstart - 1; i >= 0; --i) {
carry = 0L;
j = ystart;

for(int k = ystart + 1 + i; j >= 0; --k) {
long product = ((long)y[j] & 4294967295L) * ((long)x[i] & 4294967295L) + ((long)z[k] & 4294967295L) + carry;
z[k] = (int)product;
carry = product >>> 32;
--j;
}

z[i] = (int)carry;
}

return z;
}

private static void multiplyToLenCheck(int[] array, int length) {
if (length > 0) {
Objects.requireNonNull(array);
if (length > array.length) {
throw new ArrayIndexOutOfBoundsException(length - 1);
}
}
}

private static BigInteger multiplyKaratsuba(BigInteger x, BigInteger y) {
int xlen = x.mag.length;
int ylen = y.mag.length;
int half = (Math.max(xlen, ylen) + 1) / 2;
BigInteger xl = x.getLower(half);
BigInteger xh = x.getUpper(half);
BigInteger yl = y.getLower(half);
BigInteger yh = y.getUpper(half);
BigInteger p1 = xh.multiply(yh);
BigInteger p2 = xl.multiply(yl);
BigInteger p3 = xh.add(xl).multiply(yh.add(yl));
BigInteger result = p1.shiftLeft(32 * half).add(p3.subtract(p1).subtract(p2)).shiftLeft(32 * half).add(p2);
return x.signum != y.signum ? result.negate() : result;
}

private static BigInteger multiplyToomCook3(BigInteger a, BigInteger b) {
int alen = a.mag.length;
int blen = b.mag.length;
int largest = Math.max(alen, blen);
int k = (largest + 2) / 3;
int r = largest - 2 * k;
BigInteger a2 = a.getToomSlice(k, r, 0, largest);
BigInteger a1 = a.getToomSlice(k, r, 1, largest);
BigInteger a0 = a.getToomSlice(k, r, 2, largest);
BigInteger b2 = b.getToomSlice(k, r, 0, largest);
BigInteger b1 = b.getToomSlice(k, r, 1, largest);
BigInteger b0 = b.getToomSlice(k, r, 2, largest);
BigInteger v0 = a0.multiply(b0, true);
BigInteger da1 = a2.add(a0);
BigInteger db1 = b2.add(b0);
BigInteger vm1 = da1.subtract(a1).multiply(db1.subtract(b1), true);
da1 = da1.add(a1);
db1 = db1.add(b1);
BigInteger v1 = da1.multiply(db1, true);
BigInteger v2 = da1.add(a2).shiftLeft(1).subtract(a0).multiply(db1.add(b2).shiftLeft(1).subtract(b0), true);
BigInteger vinf = a2.multiply(b2, true);
BigInteger t2 = v2.subtract(vm1).exactDivideBy3();
BigInteger tm1 = v1.subtract(vm1).shiftRight(1);
BigInteger t1 = v1.subtract(v0);
t2 = t2.subtract(t1).shiftRight(1);
t1 = t1.subtract(tm1).subtract(vinf);
t2 = t2.subtract(vinf.shiftLeft(1));
tm1 = tm1.subtract(t2);
int ss = k * 32;
BigInteger result = vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
return a.signum != b.signum ? result.negate() : result;
}

private BigInteger getToomSlice(int lowerSize, int upperSize, int slice, int fullsize) {
int len = this.mag.length;
int offset = fullsize - len;
int start;
int end;
if (slice == 0) {
start = 0 - offset;
end = upperSize - 1 - offset;
} else {
start = upperSize + (slice - 1) * lowerSize - offset;
end = start + lowerSize - 1;
}

if (start < 0) {
start = 0;
}

if (end < 0) {
return ZERO;
} else {
int sliceSize = end - start + 1;
if (sliceSize <= 0) {
return ZERO;
} else if (start == 0 && sliceSize >= len) {
return this.abs();
} else {
int[] intSlice = new int[sliceSize];
System.arraycopy(this.mag, start, intSlice, 0, sliceSize);
return new BigInteger(trustedStripLeadingZeroInts(intSlice), 1);
}
}
}

private BigInteger exactDivideBy3() {
int len = this.mag.length;
int[] result = new int[len];
long borrow = 0L;

for(int i = len - 1; i >= 0; --i) {
long x = (long)this.mag[i] & 4294967295L;
long w = x - borrow;
if (borrow > x) {
borrow = 1L;
} else {
borrow = 0L;
}

long q = w * 2863311531L & 4294967295L;
result[i] = (int)q;
if (q >= 1431655766L) {
++borrow;
if (q >= 2863311531L) {
++borrow;
}
}
}

result = trustedStripLeadingZeroInts(result);
return new BigInteger(result, this.signum);
}

private BigInteger getLower(int n) {
int len = this.mag.length;
if (len <= n) {
return this.abs();
} else {
int[] lowerInts = new int[n];
System.arraycopy(this.mag, len - n, lowerInts, 0, n);
return new BigInteger(trustedStripLeadingZeroInts(lowerInts), 1);
}
}

private BigInteger getUpper(int n) {
int len = this.mag.length;
if (len <= n) {
return ZERO;
} else {
int upperLen = len - n;
int[] upperInts = new int[upperLen];
System.arraycopy(this.mag, 0, upperInts, 0, upperLen);
return new BigInteger(trustedStripLeadingZeroInts(upperInts), 1);
}
}

private BigInteger square() {
return this.square(false);
}

private BigInteger square(boolean isRecursion) {
if (this.signum == 0) {
return ZERO;
} else {
int len = this.mag.length;
if (len < 128) {
int[] z = squareToLen(this.mag, len, (int[])null);
return new BigInteger(trustedStripLeadingZeroInts(z), 1);
} else if (len < 216) {
return this.squareKaratsuba();
} else {
if (!isRecursion && (long)bitLength(this.mag, this.mag.length) > 1073741824L) {
reportOverflow();
}

return this.squareToomCook3();
}
}
}

private static final int[] squareToLen(int[] x, int len, int[] z) {
int zlen = len << 1;
if (z == null || z.length < zlen) {
z = new int[zlen];
}

implSquareToLenChecks(x, len, z, zlen);
return implSquareToLen(x, len, z, zlen);
}

private static void implSquareToLenChecks(int[] x, int len, int[] z, int zlen) throws RuntimeException {
if (len < 1) {
throw new IllegalArgumentException("invalid input length: " + len);
} else if (len > x.length) {
throw new IllegalArgumentException("input length out of bound: " + len + " > " + x.length);
} else if (len * 2 > z.length) {
throw new IllegalArgumentException("input length out of bound: " + len * 2 + " > " + z.length);
} else if (zlen < 1) {
throw new IllegalArgumentException("invalid input length: " + zlen);
} else if (zlen > z.length) {
throw new IllegalArgumentException("input length out of bound: " + len + " > " + z.length);
}
}

@HotSpotIntrinsicCandidate
private static final int[] implSquareToLen(int[] x, int len, int[] z, int zlen) {
int lastProductLowWord = 0;
int i = 0;

int offset;
for(offset = 0; i < len; ++i) {
long piece = (long)x[i] & 4294967295L;
long product = piece * piece;
z[offset++] = lastProductLowWord << 31 | (int)(product >>> 33);
z[offset++] = (int)(product >>> 1);
lastProductLowWord = (int)product;
}

i = len;

for(offset = 1; i > 0; offset += 2) {
int t = x[i - 1];
t = mulAdd(z, x, offset, i - 1, t);
addOne(z, offset - 1, i, t);
--i;
}

primitiveLeftShift(z, zlen, 1);
z[zlen - 1] |= x[len - 1] & 1;
return z;
}

private BigInteger squareKaratsuba() {
int half = (this.mag.length + 1) / 2;
BigInteger xl = this.getLower(half);
BigInteger xh = this.getUpper(half);
BigInteger xhs = xh.square();
BigInteger xls = xl.square();
return xhs.shiftLeft(half * 32).add(xl.add(xh).square().subtract(xhs.add(xls))).shiftLeft(half * 32).add(xls);
}

private BigInteger squareToomCook3() {
int len = this.mag.length;
int k = (len + 2) / 3;
int r = len - 2 * k;
BigInteger a2 = this.getToomSlice(k, r, 0, len);
BigInteger a1 = this.getToomSlice(k, r, 1, len);
BigInteger a0 = this.getToomSlice(k, r, 2, len);
BigInteger v0 = a0.square(true);
BigInteger da1 = a2.add(a0);
BigInteger vm1 = da1.subtract(a1).square(true);
da1 = da1.add(a1);
BigInteger v1 = da1.square(true);
BigInteger vinf = a2.square(true);
BigInteger v2 = da1.add(a2).shiftLeft(1).subtract(a0).square(true);
BigInteger t2 = v2.subtract(vm1).exactDivideBy3();
BigInteger tm1 = v1.subtract(vm1).shiftRight(1);
BigInteger t1 = v1.subtract(v0);
t2 = t2.subtract(t1).shiftRight(1);
t1 = t1.subtract(tm1).subtract(vinf);
t2 = t2.subtract(vinf.shiftLeft(1));
tm1 = tm1.subtract(t2);
int ss = k * 32;
return vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
}

public BigInteger divide(BigInteger val) {
return val.mag.length >= 80 && this.mag.length - val.mag.length >= 40 ? this.divideBurnikelZiegler(val) : this.divideKnuth(val);
}

private BigInteger divideKnuth(BigInteger val) {
MutableBigInteger q = new MutableBigInteger();
MutableBigInteger a = new MutableBigInteger(this.mag);
MutableBigInteger b = new MutableBigInteger(val.mag);
a.divideKnuth(b, q, false);
return q.toBigInteger(this.signum * val.signum);
}

public BigInteger[] divideAndRemainder(BigInteger val) {
return val.mag.length >= 80 && this.mag.length - val.mag.length >= 40 ? this.divideAndRemainderBurnikelZiegler(val) : this.divideAndRemainderKnuth(val);
}

private BigInteger[] divideAndRemainderKnuth(BigInteger val) {
BigInteger[] result = new BigInteger[2];
MutableBigInteger q = new MutableBigInteger();
MutableBigInteger a = new MutableBigInteger(this.mag);
MutableBigInteger b = new MutableBigInteger(val.mag);
MutableBigInteger r = a.divideKnuth(b, q);
result[0] = q.toBigInteger(this.signum == val.signum ? 1 : -1);
result[1] = r.toBigInteger(this.signum);
return result;
}

public BigInteger remainder(BigInteger val) {
return val.mag.length >= 80 && this.mag.length - val.mag.length >= 40 ? this.remainderBurnikelZiegler(val) : this.remainderKnuth(val);
}

private BigInteger remainderKnuth(BigInteger val) {
MutableBigInteger q = new MutableBigInteger();
MutableBigInteger a = new MutableBigInteger(this.mag);
MutableBigInteger b = new MutableBigInteger(val.mag);
return a.divideKnuth(b, q).toBigInteger(this.signum);
}

private BigInteger divideBurnikelZiegler(BigInteger val) {
return this.divideAndRemainderBurnikelZiegler(val)[0];
}

private BigInteger remainderBurnikelZiegler(BigInteger val) {
return this.divideAndRemainderBurnikelZiegler(val)[1];
}

private BigInteger[] divideAndRemainderBurnikelZiegler(BigInteger val) {
MutableBigInteger q = new MutableBigInteger();
MutableBigInteger r = (new MutableBigInteger(this)).divideAndRemainderBurnikelZiegler(new MutableBigInteger(val), q);
BigInteger qBigInt = q.isZero() ? ZERO : q.toBigInteger(this.signum * val.signum);
BigInteger rBigInt = r.isZero() ? ZERO : r.toBigInteger(this.signum);
return new BigInteger[]{qBigInt, rBigInt};
}

public BigInteger pow(int exponent) {
if (exponent < 0) {
throw new ArithmeticException("Negative exponent");
} else if (this.signum == 0) {
return exponent == 0 ? ONE : this;
} else {
BigInteger partToSquare = this.abs();
int powersOfTwo = partToSquare.getLowestSetBit();
long bitsToShiftLong = (long)powersOfTwo * (long)exponent;
if (bitsToShiftLong > 2147483647L) {
reportOverflow();
}

int bitsToShift = (int)bitsToShiftLong;
int remainingBits;
if (powersOfTwo > 0) {
partToSquare = partToSquare.shiftRight(powersOfTwo);
remainingBits = partToSquare.bitLength();
if (remainingBits == 1) {
if (this.signum < 0 && (exponent & 1) == 1) {
return NEGATIVE_ONE.shiftLeft(bitsToShift);
}

return ONE.shiftLeft(bitsToShift);
}
} else {
remainingBits = partToSquare.bitLength();
if (remainingBits == 1) {
if (this.signum < 0 && (exponent & 1) == 1) {
return NEGATIVE_ONE;
}

return ONE;
}
}

long scaleFactor = (long)remainingBits * (long)exponent;
if (partToSquare.mag.length == 1 && scaleFactor <= 62L) {
int newSign = this.signum < 0 && (exponent & 1) == 1 ? -1 : 1;
long result = 1L;
long baseToPow2 = (long)partToSquare.mag[0] & 4294967295L;
int workingExponent = exponent;

while(workingExponent != 0) {
if ((workingExponent & 1) == 1) {
result *= baseToPow2;
}

if ((workingExponent >>>= 1) != 0) {
baseToPow2 *= baseToPow2;
}
}

if (powersOfTwo > 0) {
if ((long)bitsToShift + scaleFactor <= 62L) {
return valueOf((result << bitsToShift) * (long)newSign);
} else {
return valueOf(result * (long)newSign).shiftLeft(bitsToShift);
}
} else {
return valueOf(result * (long)newSign);
}
} else {
if ((long)this.bitLength() * (long)exponent / 32L > 67108864L) {
reportOverflow();
}

BigInteger answer = ONE;
int workingExponent = exponent;

while(workingExponent != 0) {
if ((workingExponent & 1) == 1) {
answer = answer.multiply(partToSquare);
}

if ((workingExponent >>>= 1) != 0) {
partToSquare = partToSquare.square();
}
}

if (powersOfTwo > 0) {
answer = answer.shiftLeft(bitsToShift);
}

if (this.signum < 0 && (exponent & 1) == 1) {
return answer.negate();
} else {
return answer;
}
}
}
}

public BigInteger sqrt() {
if (this.signum < 0) {
throw new ArithmeticException("Negative BigInteger");
} else {
return (new MutableBigInteger(this.mag)).sqrt().toBigInteger();
}
}

public BigInteger[] sqrtAndRemainder() {
BigInteger s = this.sqrt();
BigInteger r = this.subtract(s.square());

assert r.compareTo(ZERO) >= 0;

return new BigInteger[]{s, r};
}

public BigInteger gcd(BigInteger val) {
if (val.signum == 0) {
return this.abs();
} else if (this.signum == 0) {
return val.abs();
} else {
MutableBigInteger a = new MutableBigInteger(this);
MutableBigInteger b = new MutableBigInteger(val);
MutableBigInteger result = a.hybridGCD(b);
return result.toBigInteger(1);
}
}

static int bitLengthForInt(int n) {
return 32 - Integer.numberOfLeadingZeros(n);
}

private static int[] leftShift(int[] a, int len, int n) {
int nInts = n >>> 5;
int nBits = n & 31;
int bitsInHighWord = bitLengthForInt(a[0]);
if (n <= 32 - bitsInHighWord) {
primitiveLeftShift(a, len, nBits);
return a;
} else {
int[] result;
if (nBits <= 32 - bitsInHighWord) {
result = new int[nInts + len];
System.arraycopy(a, 0, result, 0, len);
primitiveLeftShift(result, result.length, nBits);
return result;
} else {
result = new int[nInts + len + 1];
System.arraycopy(a, 0, result, 0, len);
primitiveRightShift(result, result.length, 32 - nBits);
return result;
}
}
}

static void primitiveRightShift(int[] a, int len, int n) {
int n2 = 32 - n;
int i = len - 1;

for(int c = a[i]; i > 0; --i) {
int b = c;
c = a[i - 1];
a[i] = c << n2 | b >>> n;
}

a[0] >>>= n;
}

static void primitiveLeftShift(int[] a, int len, int n) {
if (len != 0 && n != 0) {
int n2 = 32 - n;
int i = 0;
int c = a[i];

for(int m = i + len - 1; i < m; ++i) {
int b = c;
c = a[i + 1];
a[i] = b << n | c >>> n2;
}

a[len - 1] <<= n;
}
}

private static int bitLength(int[] val, int len) {
return len == 0 ? 0 : (len - 1 << 5) + bitLengthForInt(val[0]);
}

public BigInteger abs() {
return this.signum >= 0 ? this : this.negate();
}

public BigInteger negate() {
return new BigInteger(this.mag, -this.signum);
}

public int signum() {
return this.signum;
}

public BigInteger mod(BigInteger m) {
if (m.signum <= 0) {
throw new ArithmeticException("BigInteger: modulus not positive");
} else {
BigInteger result = this.remainder(m);
return result.signum >= 0 ? result : result.add(m);
}
}

public BigInteger modPow(BigInteger exponent, BigInteger m) {
if (m.signum <= 0) {
throw new ArithmeticException("BigInteger: modulus not positive");
} else if (exponent.signum == 0) {
return m.equals(ONE) ? ZERO : ONE;
} else if (this.equals(ONE)) {
return m.equals(ONE) ? ZERO : ONE;
} else if (this.equals(ZERO) && exponent.signum >= 0) {
return ZERO;
} else if (this.equals(negConst[1]) && !exponent.testBit(0)) {
return m.equals(ONE) ? ZERO : ONE;
} else {
boolean invertResult;
if (invertResult = exponent.signum < 0) {
exponent = exponent.negate();
}

BigInteger base = this.signum >= 0 && this.compareTo(m) < 0 ? this : this.mod(m);
BigInteger result;
if (m.testBit(0)) {
result = base.oddModPow(exponent, m);
} else {
int p = m.getLowestSetBit();
BigInteger m1 = m.shiftRight(p);
BigInteger m2 = ONE.shiftLeft(p);
BigInteger base2 = this.signum >= 0 && this.compareTo(m1) < 0 ? this : this.mod(m1);
BigInteger a1 = m1.equals(ONE) ? ZERO : base2.oddModPow(exponent, m1);
BigInteger a2 = base.modPow2(exponent, p);
BigInteger y1 = m2.modInverse(m1);
BigInteger y2 = m1.modInverse(m2);
if (m.mag.length < 33554432) {
result = a1.multiply(m2).multiply(y1).add(a2.multiply(m1).multiply(y2)).mod(m);
} else {
MutableBigInteger t1 = new MutableBigInteger();
(new MutableBigInteger(a1.multiply(m2))).multiply(new MutableBigInteger(y1), t1);
MutableBigInteger t2 = new MutableBigInteger();
(new MutableBigInteger(a2.multiply(m1))).multiply(new MutableBigInteger(y2), t2);
t1.add(t2);
MutableBigInteger q = new MutableBigInteger();
result = t1.divide(new MutableBigInteger(m), q).toBigInteger();
}
}

return invertResult ? result.modInverse(m) : result;
}
}

private static int[] montgomeryMultiply(int[] a, int[] b, int[] n, int len, long inv, int[] product) {
implMontgomeryMultiplyChecks(a, b, n, len, product);
if (len > 512) {
product = multiplyToLen(a, len, b, len, product);
return montReduce(product, n, len, (int)inv);
} else {
return implMontgomeryMultiply(a, b, n, len, inv, materialize(product, len));
}
}

private static int[] montgomerySquare(int[] a, int[] n, int len, long inv, int[] product) {
implMontgomeryMultiplyChecks(a, a, n, len, product);
if (len > 512) {
product = squareToLen(a, len, product);
return montReduce(product, n, len, (int)inv);
} else {
return implMontgomerySquare(a, n, len, inv, materialize(product, len));
}
}

private static void implMontgomeryMultiplyChecks(int[] a, int[] b, int[] n, int len, int[] product) throws RuntimeException {
if (len % 2 != 0) {
throw new IllegalArgumentException("input array length must be even: " + len);
} else if (len < 1) {
throw new IllegalArgumentException("invalid input length: " + len);
} else if (len > a.length || len > b.length || len > n.length || product != null && len > product.length) {
throw new IllegalArgumentException("input array length out of bound: " + len);
}
}

private static int[] materialize(int[] z, int len) {
if (z == null || z.length < len) {
z = new int[len];
}

return z;
}

@HotSpotIntrinsicCandidate
private static int[] implMontgomeryMultiply(int[] a, int[] b, int[] n, int len, long inv, int[] product) {
product = multiplyToLen(a, len, b, len, product);
return montReduce(product, n, len, (int)inv);
}

@HotSpotIntrinsicCandidate
private static int[] implMontgomerySquare(int[] a, int[] n, int len, long inv, int[] product) {
product = squareToLen(a, len, product);
return montReduce(product, n, len, (int)inv);
}

private BigInteger oddModPow(BigInteger y, BigInteger z) {
if (y.equals(ONE)) {
return this;
} else if (this.signum == 0) {
return ZERO;
} else {
int[] base = (int[])this.mag.clone();
int[] exp = y.mag;
int[] mod = z.mag;
int modLen = mod.length;
if ((modLen & 1) != 0) {
int[] x = new int[modLen + 1];
System.arraycopy(mod, 0, x, 1, modLen);
mod = x;
++modLen;
}

int wbits = 0;
int ebits = bitLength(exp, exp.length);
if (ebits != 17 || exp[0] != 65537) {
while(ebits > bnExpModThreshTable[wbits]) {
++wbits;
}
}

int tblmask = 1 << wbits;
int[][] table = new int[tblmask][];

for(int i = 0; i < tblmask; ++i) {
table[i] = new int[modLen];
}

long n0 = ((long)mod[modLen - 1] & 4294967295L) + (((long)mod[modLen - 2] & 4294967295L) << 32);
long inv = -MutableBigInteger.inverseMod64(n0);
int[] a = leftShift(base, base.length, modLen << 5);
MutableBigInteger q = new MutableBigInteger();
MutableBigInteger a2 = new MutableBigInteger(a);
MutableBigInteger b2 = new MutableBigInteger(mod);
b2.normalize();
MutableBigInteger r = a2.divide(b2, q);
table[0] = r.toIntArray();
int[] t;
if (table[0].length < modLen) {
int offset = modLen - table[0].length;
t = new int[modLen];
System.arraycopy(table[0], 0, t, offset, table[0].length);
table[0] = t;
}

int[] b = montgomerySquare(table[0], mod, modLen, inv, (int[])null);
t = Arrays.copyOf(b, modLen);

int bitpos;
for(bitpos = 1; bitpos < tblmask; ++bitpos) {
table[bitpos] = montgomeryMultiply(t, table[bitpos - 1], mod, modLen, inv, (int[])null);
}

bitpos = 1 << (ebits - 1 & 31);
int buf = 0;
int elen = exp.length;
int eIndex = 0;

int multpos;
for(multpos = 0; multpos <= wbits; ++multpos) {
buf = buf << 1 | ((exp[eIndex] & bitpos) != 0 ? 1 : 0);
bitpos >>>= 1;
if (bitpos == 0) {
++eIndex;
bitpos = -2147483648;
--elen;
}
}

--ebits;
boolean isone = true;

for(multpos = ebits - wbits; (buf & 1) == 0; ++multpos) {
buf >>>= 1;
}

int[] mult = table[buf >>> 1];
buf = 0;
if (multpos == ebits) {
isone = false;
}

while(true) {
--ebits;
buf <<= 1;
if (elen != 0) {
buf |= (exp[eIndex] & bitpos) != 0 ? 1 : 0;
bitpos >>>= 1;
if (bitpos == 0) {
++eIndex;
bitpos = -2147483648;
--elen;
}
}

if ((buf & tblmask) != 0) {
for(multpos = ebits - wbits; (buf & 1) == 0; ++multpos) {
buf >>>= 1;
}

mult = table[buf >>> 1];
buf = 0;
}

if (ebits == multpos) {
if (isone) {
b = (int[])mult.clone();
isone = false;
} else {
a = montgomeryMultiply(b, mult, mod, modLen, inv, a);
t = a;
a = b;
b = t;
}
}

if (ebits == 0) {
int[] t2 = new int[2 * modLen];
System.arraycopy(b, 0, t2, modLen, modLen);
b = montReduce(t2, mod, modLen, (int)inv);
t2 = Arrays.copyOf(b, modLen);
return new BigInteger(1, t2);
}

if (!isone) {
a = montgomerySquare(b, mod, modLen, inv, a);
t = a;
a = b;
b = t;
}
}
}
}

private static int[] montReduce(int[] n, int[] mod, int mlen, int inv) {
int c = 0;
int len = mlen;
int offset = 0;

do {
int nEnd = n[n.length - 1 - offset];
int carry = mulAdd(n, mod, offset, mlen, inv * nEnd);
c += addOne(n, offset, mlen, carry);
++offset;
--len;
} while(len > 0);

while(c > 0) {
c += subN(n, mod, mlen);
}

while(intArrayCmpToLen(n, mod, mlen) >= 0) {
subN(n, mod, mlen);
}

return n;
}

private static int intArrayCmpToLen(int[] arg1, int[] arg2, int len) {
for(int i = 0; i < len; ++i) {
long b1 = (long)arg1[i] & 4294967295L;
long b2 = (long)arg2[i] & 4294967295L;
if (b1 < b2) {
return -1;
}

if (b1 > b2) {
return 1;
}
}

return 0;
}

private static int subN(int[] a, int[] b, int len) {
long sum = 0L;

while(true) {
--len;
if (len < 0) {
return (int)(sum >> 32);
}

sum = ((long)a[len] & 4294967295L) - ((long)b[len] & 4294967295L) + (sum >> 32);
a[len] = (int)sum;
}
}

static int mulAdd(int[] out, int[] in, int offset, int len, int k) {
implMulAddCheck(out, in, offset, len, k);
return implMulAdd(out, in, offset, len, k);
}

private static void implMulAddCheck(int[] out, int[] in, int offset, int len, int k) {
if (len > in.length) {
throw new IllegalArgumentException("input length is out of bound: " + len + " > " + in.length);
} else if (offset < 0) {
throw new IllegalArgumentException("input offset is invalid: " + offset);
} else if (offset > out.length - 1) {
throw new IllegalArgumentException("input offset is out of bound: " + offset + " > " + (out.length - 1));
} else if (len > out.length - offset) {
throw new IllegalArgumentException("input len is out of bound: " + len + " > " + (out.length - offset));
}
}

@HotSpotIntrinsicCandidate
private static int implMulAdd(int[] out, int[] in, int offset, int len, int k) {
long kLong = (long)k & 4294967295L;
long carry = 0L;
offset = out.length - offset - 1;

for(int j = len - 1; j >= 0; --j) {
long product = ((long)in[j] & 4294967295L) * kLong + ((long)out[offset] & 4294967295L) + carry;
out[offset--] = (int)product;
carry = product >>> 32;
}

return (int)carry;
}

static int addOne(int[] a, int offset, int mlen, int carry) {
offset = a.length - 1 - mlen - offset;
long t = ((long)a[offset] & 4294967295L) + ((long)carry & 4294967295L);
a[offset] = (int)t;
if (t >>> 32 == 0L) {
return 0;
} else {
do {
--mlen;
if (mlen < 0) {
return 1;
}

--offset;
if (offset < 0) {
return 1;
}

int var10002 = a[offset]++;
} while(a[offset] == 0);

return 0;
}
}

private BigInteger modPow2(BigInteger exponent, int p) {
BigInteger result = ONE;
BigInteger baseToPow2 = this.mod2(p);
int expOffset = 0;
int limit = exponent.bitLength();
if (this.testBit(0)) {
limit = p - 1 < limit ? p - 1 : limit;
}

while(expOffset < limit) {
if (exponent.testBit(expOffset)) {
result = result.multiply(baseToPow2).mod2(p);
}

++expOffset;
if (expOffset < limit) {
baseToPow2 = baseToPow2.square().mod2(p);
}
}

return result;
}

private BigInteger mod2(int p) {
if (this.bitLength() <= p) {
return this;
} else {
int numInts = p + 31 >>> 5;
int[] mag = new int[numInts];
System.arraycopy(this.mag, this.mag.length - numInts, mag, 0, numInts);
int excessBits = (numInts << 5) - p;
mag[0] = (int)((long)mag[0] & (1L << 32 - excessBits) - 1L);
return mag[0] == 0 ? new BigInteger(1, mag) : new BigInteger(mag, 1);
}
}

public BigInteger modInverse(BigInteger m) {
if (m.signum != 1) {
throw new ArithmeticException("BigInteger: modulus not positive");
} else if (m.equals(ONE)) {
return ZERO;
} else {
BigInteger modVal = this;
if (this.signum < 0 || this.compareMagnitude(m) >= 0) {
modVal = this.mod(m);
}

if (modVal.equals(ONE)) {
return ONE;
} else {
MutableBigInteger a = new MutableBigInteger(modVal);
MutableBigInteger b = new MutableBigInteger(m);
MutableBigInteger result = a.mutableModInverse(b);
return result.toBigInteger(1);
}
}
}

public BigInteger shiftLeft(int n) {
if (this.signum == 0) {
return ZERO;
} else if (n > 0) {
return new BigInteger(shiftLeft(this.mag, n), this.signum);
} else {
return n == 0 ? this : this.shiftRightImpl(-n);
}
}

private static int[] shiftLeft(int[] mag, int n) {
int nInts = n >>> 5;
int nBits = n & 31;
int magLen = mag.length;
int[] newMag = null;
int[] newMag;
if (nBits == 0) {
newMag = new int[magLen + nInts];
System.arraycopy(mag, 0, newMag, 0, magLen);
} else {
int i = 0;
int nBits2 = 32 - nBits;
int highBits = mag[0] >>> nBits2;
if (highBits != 0) {
newMag = new int[magLen + nInts + 1];
newMag[i++] = highBits;
} else {
newMag = new int[magLen + nInts];
}

int j;
for(j = 0; j < magLen - 1; newMag[i++] = mag[j++] << nBits | mag[j] >>> nBits2) {
}

newMag[i] = mag[j] << nBits;
}

return newMag;
}

public BigInteger shiftRight(int n) {
if (this.signum == 0) {
return ZERO;
} else if (n > 0) {
return this.shiftRightImpl(n);
} else {
return n == 0 ? this : new BigInteger(shiftLeft(this.mag, -n), this.signum);
}
}

private BigInteger shiftRightImpl(int n) {
int nInts = n >>> 5;
int nBits = n & 31;
int magLen = this.mag.length;
int[] newMag = null;
if (nInts >= magLen) {
return this.signum >= 0 ? ZERO : negConst[1];
} else {
int newMagLen;
int i;
int nBits2;
int[] newMag;
if (nBits == 0) {
newMagLen = magLen - nInts;
newMag = Arrays.copyOf(this.mag, newMagLen);
} else {
newMagLen = 0;
i = this.mag[0] >>> nBits;
if (i != 0) {
newMag = new int[magLen - nInts];
newMag[newMagLen++] = i;
} else {
newMag = new int[magLen - nInts - 1];
}

nBits2 = 32 - nBits;

for(int j = 0; j < magLen - nInts - 1; newMag[newMagLen++] = this.mag[j++] << nBits2 | this.mag[j] >>> nBits) {
}
}

if (this.signum < 0) {
boolean onesLost = false;
i = magLen - 1;

for(nBits2 = magLen - nInts; i >= nBits2 && !onesLost; --i) {
onesLost = this.mag[i] != 0;
}

if (!onesLost && nBits != 0) {
onesLost = this.mag[magLen - nInts - 1] << 32 - nBits != 0;
}

if (onesLost) {
newMag = this.javaIncrement(newMag);
}
}

return new BigInteger(newMag, this.signum);
}
}

int[] javaIncrement(int[] val) {
int lastSum = 0;

for(int i = val.length - 1; i >= 0 && lastSum == 0; --i) {
lastSum = ++val[i];
}

if (lastSum == 0) {
val = new int[val.length + 1];
val[0] = 1;
}

return val;
}

public BigInteger and(BigInteger val) {
int[] result = new int[Math.max(this.intLength(), val.intLength())];

for(int i = 0; i < result.length; ++i) {
result[i] = this.getInt(result.length - i - 1) & val.getInt(result.length - i - 1);
}

return valueOf(result);
}

public BigInteger or(BigInteger val) {
int[] result = new int[Math.max(this.intLength(), val.intLength())];

for(int i = 0; i < result.length; ++i) {
result[i] = this.getInt(result.length - i - 1) | val.getInt(result.length - i - 1);
}

return valueOf(result);
}

public BigInteger xor(BigInteger val) {
int[] result = new int[Math.max(this.intLength(), val.intLength())];

for(int i = 0; i < result.length; ++i) {
result[i] = this.getInt(result.length - i - 1) ^ val.getInt(result.length - i - 1);
}

return valueOf(result);
}

public BigInteger not() {
int[] result = new int[this.intLength()];

for(int i = 0; i < result.length; ++i) {
result[i] = ~this.getInt(result.length - i - 1);
}

return valueOf(result);
}

public BigInteger andNot(BigInteger val) {
int[] result = new int[Math.max(this.intLength(), val.intLength())];

for(int i = 0; i < result.length; ++i) {
result[i] = this.getInt(result.length - i - 1) & ~val.getInt(result.length - i - 1);
}

return valueOf(result);
}

public boolean testBit(int n) {
if (n < 0) {
throw new ArithmeticException("Negative bit address");
} else {
return (this.getInt(n >>> 5) & 1 << (n & 31)) != 0;
}
}

public BigInteger setBit(int n) {
if (n < 0) {
throw new ArithmeticException("Negative bit address");
} else {
int intNum = n >>> 5;
int[] result = new int[Math.max(this.intLength(), intNum + 2)];

for(int i = 0; i < result.length; ++i) {
result[result.length - i - 1] = this.getInt(i);
}

result[result.length - intNum - 1] |= 1 << (n & 31);
return valueOf(result);
}
}

public BigInteger clearBit(int n) {
if (n < 0) {
throw new ArithmeticException("Negative bit address");
} else {
int intNum = n >>> 5;
int[] result = new int[Math.max(this.intLength(), (n + 1 >>> 5) + 1)];

for(int i = 0; i < result.length; ++i) {
result[result.length - i - 1] = this.getInt(i);
}

result[result.length - intNum - 1] &= ~(1 << (n & 31));
return valueOf(result);
}
}

public BigInteger flipBit(int n) {
if (n < 0) {
throw new ArithmeticException("Negative bit address");
} else {
int intNum = n >>> 5;
int[] result = new int[Math.max(this.intLength(), intNum + 2)];

for(int i = 0; i < result.length; ++i) {
result[result.length - i - 1] = this.getInt(i);
}

result[result.length - intNum - 1] ^= 1 << (n & 31);
return valueOf(result);
}
}

public int getLowestSetBit() {
int lsb = this.lowestSetBitPlusTwo - 2;
if (lsb == -2) {
int lsb = 0;
if (this.signum == 0) {
lsb = lsb - 1;
} else {
int i;
int b;
for(i = 0; (b = this.getInt(i)) == 0; ++i) {
}

lsb = lsb + (i << 5) + Integer.numberOfTrailingZeros(b);
}

this.lowestSetBitPlusTwo = lsb + 2;
}

return lsb;
}

public int bitLength() {
int n = this.bitLengthPlusOne - 1;
if (n == -1) {
int[] m = this.mag;
int len = m.length;
if (len == 0) {
n = 0;
} else {
int magBitLength = (len - 1 << 5) + bitLengthForInt(this.mag[0]);
if (this.signum >= 0) {
n = magBitLength;
} else {
boolean pow2 = Integer.bitCount(this.mag[0]) == 1;

for(int i = 1; i < len && pow2; ++i) {
pow2 = this.mag[i] == 0;
}

n = pow2 ? magBitLength - 1 : magBitLength;
}
}

this.bitLengthPlusOne = n + 1;
}

return n;
}

public int bitCount() {
int bc = this.bitCountPlusOne - 1;
if (bc == -1) {
bc = 0;

int magTrailingZeroCount;
for(magTrailingZeroCount = 0; magTrailingZeroCount < this.mag.length; ++magTrailingZeroCount) {
bc += Integer.bitCount(this.mag[magTrailingZeroCount]);
}

if (this.signum < 0) {
magTrailingZeroCount = 0;

int j;
for(j = this.mag.length - 1; this.mag[j] == 0; --j) {
magTrailingZeroCount += 32;
}

magTrailingZeroCount += Integer.numberOfTrailingZeros(this.mag[j]);
bc += magTrailingZeroCount - 1;
}

this.bitCountPlusOne = bc + 1;
}

return bc;
}

public boolean isProbablePrime(int certainty) {
if (certainty <= 0) {
return true;
} else {
BigInteger w = this.abs();
if (w.equals(TWO)) {
return true;
} else {
return w.testBit(0) && !w.equals(ONE) ? w.primeToCertainty(certainty, (Random)null) : false;
}
}
}

public int compareTo(BigInteger val) {
if (this.signum == val.signum) {
switch(this.signum) {
case -1:
return val.compareMagnitude(this);
case 1:
return this.compareMagnitude(val);
default:
return 0;
}
} else {
return this.signum > val.signum ? 1 : -1;
}
}

final int compareMagnitude(BigInteger val) {
int[] m1 = this.mag;
int len1 = m1.length;
int[] m2 = val.mag;
int len2 = m2.length;
if (len1 < len2) {
return -1;
} else if (len1 > len2) {
return 1;
} else {
for(int i = 0; i < len1; ++i) {
int a = m1[i];
int b = m2[i];
if (a != b) {
return ((long)a & 4294967295L) < ((long)b & 4294967295L) ? -1 : 1;
}
}

return 0;
}
}

final int compareMagnitude(long val) {
assert val != -9223372036854775808L;

int[] m1 = this.mag;
int len = m1.length;
if (len > 2) {
return 1;
} else {
if (val < 0L) {
val = -val;
}

int highWord = (int)(val >>> 32);
int a;
int b;
if (highWord == 0) {
if (len < 1) {
return -1;
} else if (len > 1) {
return 1;
} else {
a = m1[0];
b = (int)val;
if (a != b) {
return ((long)a & 4294967295L) < ((long)b & 4294967295L) ? -1 : 1;
} else {
return 0;
}
}
} else if (len < 2) {
return -1;
} else {
a = m1[0];
if (a != highWord) {
return ((long)a & 4294967295L) < ((long)highWord & 4294967295L) ? -1 : 1;
} else {
a = m1[1];
b = (int)val;
if (a != b) {
return ((long)a & 4294967295L) < ((long)b & 4294967295L) ? -1 : 1;
} else {
return 0;
}
}
}
}
}

public boolean equals(Object x) {
if (x == this) {
return true;
} else if (!(x instanceof BigInteger)) {
return false;
} else {
BigInteger xInt = (BigInteger)x;
if (xInt.signum != this.signum) {
return false;
} else {
int[] m = this.mag;
int len = m.length;
int[] xm = xInt.mag;
if (len != xm.length) {
return false;
} else {
for(int i = 0; i < len; ++i) {
if (xm[i] != m[i]) {
return false;
}
}

return true;
}
}
}
}

public BigInteger min(BigInteger val) {
return this.compareTo(val) < 0 ? this : val;
}

public BigInteger max(BigInteger val) {
return this.compareTo(val) > 0 ? this : val;
}

public int hashCode() {
int hashCode = 0;

for(int i = 0; i < this.mag.length; ++i) {
hashCode = (int)((long)(31 * hashCode) + ((long)this.mag[i] & 4294967295L));
}

return hashCode * this.signum;
}

public String toString(int radix) {
if (this.signum == 0) {
return "0";
} else {
if (radix < 2 || radix > 36) {
radix = 10;
}

if (this.mag.length <= 20) {
return this.smallToString(radix);
} else {
StringBuilder sb = new StringBuilder();
if (this.signum < 0) {
toString(this.negate(), sb, radix, 0);
sb.insert(0, '-');
} else {
toString(this, sb, radix, 0);
}

return sb.toString();
}
}
}

private String smallToString(int radix) {
if (this.signum == 0) {
return "0";
} else {
int maxNumDigitGroups = (4 * this.mag.length + 6) / 7;
String[] digitGroup = new String[maxNumDigitGroups];
BigInteger tmp = this.abs();

int numGroups;
BigInteger q2;
for(numGroups = 0; tmp.signum != 0; tmp = q2) {
BigInteger d = longRadix[radix];
MutableBigInteger q = new MutableBigInteger();
MutableBigInteger a = new MutableBigInteger(tmp.mag);
MutableBigInteger b = new MutableBigInteger(d.mag);
MutableBigInteger r = a.divide(b, q);
q2 = q.toBigInteger(tmp.signum * d.signum);
BigInteger r2 = r.toBigInteger(tmp.signum * d.signum);
digitGroup[numGroups++] = Long.toString(r2.longValue(), radix);
}

StringBuilder buf = new StringBuilder(numGroups * digitsPerLong[radix] + 1);
if (this.signum < 0) {
buf.append('-');
}

buf.append(digitGroup[numGroups - 1]);

for(int i = numGroups - 2; i >= 0; --i) {
int numLeadingZeros = digitsPerLong[radix] - digitGroup[i].length();
if (numLeadingZeros != 0) {
buf.append(zeros[numLeadingZeros]);
}

buf.append(digitGroup[i]);
}

return buf.toString();
}
}

private static void toString(BigInteger u, StringBuilder sb, int radix, int digits) {
int i;
if (u.mag.length > 20) {
int b = u.bitLength();
i = (int)Math.round(Math.log((double)b * LOG_TWO / logCache[radix]) / LOG_TWO - 1.0D);
BigInteger v = getRadixConversionCache(radix, i);
BigInteger[] results = u.divideAndRemainder(v);
int expectedDigits = 1 << i;
toString(results[0], sb, radix, digits - expectedDigits);
toString(results[1], sb, radix, expectedDigits);
} else {
String s = u.smallToString(radix);
if (s.length() < digits && sb.length() > 0) {
for(i = s.length(); i < digits; ++i) {
sb.append('0');
}
}

sb.append(s);
}
}

private static BigInteger getRadixConversionCache(int radix, int exponent) {
BigInteger[] cacheLine = powerCache[radix];
if (exponent < cacheLine.length) {
return cacheLine[exponent];
} else {
int oldLength = cacheLine.length;
cacheLine = (BigInteger[])Arrays.copyOf(cacheLine, exponent + 1);

for(int i = oldLength; i <= exponent; ++i) {
cacheLine[i] = cacheLine[i - 1].pow(2);
}

BigInteger[][] pc = powerCache;
if (exponent >= pc[radix].length) {
pc = (BigInteger[][])pc.clone();
pc[radix] = cacheLine;
powerCache = pc;
}

return cacheLine[exponent];
}
}

public String toString() {
return this.toString(10);
}

public byte[] toByteArray() {
int byteLen = this.bitLength() / 8 + 1;
byte[] byteArray = new byte[byteLen];
int i = byteLen - 1;
int bytesCopied = 4;
int nextInt = 0;

for(int var6 = 0; i >= 0; --i) {
if (bytesCopied == 4) {
nextInt = this.getInt(var6++);
bytesCopied = 1;
} else {
nextInt >>>= 8;
++bytesCopied;
}

byteArray[i] = (byte)nextInt;
}

return byteArray;
}

public int intValue() {
int result = false;
int result = this.getInt(0);
return result;
}

public long longValue() {
long result = 0L;

for(int i = 1; i >= 0; --i) {
result = (result << 32) + ((long)this.getInt(i) & 4294967295L);
}

return result;
}

public float floatValue() {
if (this.signum == 0) {
return 0.0F;
} else {
int exponent = (this.mag.length - 1 << 5) + bitLengthForInt(this.mag[0]) - 1;
if (exponent < 63) {
return (float)this.longValue();
} else if (exponent > 127) {
return this.signum > 0 ? 1.0F / 0.0 : -1.0F / 0.0;
} else {
int shift = exponent - 24;
int nBits = shift & 31;
int nBits2 = 32 - nBits;
int twiceSignifFloor;
if (nBits == 0) {
twiceSignifFloor = this.mag[0];
} else {
twiceSignifFloor = this.mag[0] >>> nBits;
if (twiceSignifFloor == 0) {
twiceSignifFloor = this.mag[0] << nBits2 | this.mag[1] >>> nBits;
}
}

int signifFloor = twiceSignifFloor >> 1;
signifFloor &= 8388607;
boolean increment = (twiceSignifFloor & 1) != 0 && ((signifFloor & 1) != 0 || this.abs().getLowestSetBit() < shift);
int signifRounded = increment ? signifFloor + 1 : signifFloor;
int bits = exponent + 127 << 23;
bits += signifRounded;
bits |= this.signum & -2147483648;
return Float.intBitsToFloat(bits);
}
}
}

public double doubleValue() {
if (this.signum == 0) {
return 0.0D;
} else {
int exponent = (this.mag.length - 1 << 5) + bitLengthForInt(this.mag[0]) - 1;
if (exponent < 63) {
return (double)this.longValue();
} else if (exponent > 1023) {
return this.signum > 0 ? 1.0D / 0.0 : -1.0D / 0.0;
} else {
int shift = exponent - 53;
int nBits = shift & 31;
int nBits2 = 32 - nBits;
int highBits;
int lowBits;
if (nBits == 0) {
highBits = this.mag[0];
lowBits = this.mag[1];
} else {
highBits = this.mag[0] >>> nBits;
lowBits = this.mag[0] << nBits2 | this.mag[1] >>> nBits;
if (highBits == 0) {
highBits = lowBits;
lowBits = this.mag[1] << nBits2 | this.mag[2] >>> nBits;
}
}

long twiceSignifFloor = ((long)highBits & 4294967295L) << 32 | (long)lowBits & 4294967295L;
long signifFloor = twiceSignifFloor >> 1;
signifFloor &= 4503599627370495L;
boolean increment = (twiceSignifFloor & 1L) != 0L && ((signifFloor & 1L) != 0L || this.abs().getLowestSetBit() < shift);
long signifRounded = increment ? signifFloor + 1L : signifFloor;
long bits = (long)(exponent + 1023) << 52;
bits += signifRounded;
bits |= (long)this.signum & -9223372036854775808L;
return Double.longBitsToDouble(bits);
}
}
}

private static int[] stripLeadingZeroInts(int[] val) {
int vlen = val.length;

int keep;
for(keep = 0; keep < vlen && val[keep] == 0; ++keep) {
}

return Arrays.copyOfRange(val, keep, vlen);
}

private static int[] trustedStripLeadingZeroInts(int[] val) {
int vlen = val.length;

int keep;
for(keep = 0; keep < vlen && val[keep] == 0; ++keep) {
}

return keep == 0 ? val : Arrays.copyOfRange(val, keep, vlen);
}

private static int[] stripLeadingZeroBytes(byte[] a, int off, int len) {
int indexBound = off + len;

int keep;
for(keep = off; keep < indexBound && a[keep] == 0; ++keep) {
}

int intLength = indexBound - keep + 3 >>> 2;
int[] result = new int[intLength];
int b = indexBound - 1;

for(int i = intLength - 1; i >= 0; --i) {
result[i] = a[b--] & 255;
int bytesRemaining = b - keep + 1;
int bytesToTransfer = Math.min(3, bytesRemaining);

for(int j = 8; j <= bytesToTransfer << 3; j += 8) {
result[i] |= (a[b--] & 255) << j;
}
}

return result;
}

private static int[] makePositive(byte[] a, int off, int len) {
int indexBound = off + len;

int keep;
for(keep = off; keep < indexBound && a[keep] == -1; ++keep) {
}

int k;
for(k = keep; k < indexBound && a[k] == 0; ++k) {
}

int extraByte = k == indexBound ? 1 : 0;
int intLength = indexBound - keep + extraByte + 3 >>> 2;
int[] result = new int[intLength];
int b = indexBound - 1;

int i;
for(i = intLength - 1; i >= 0; --i) {
result[i] = a[b--] & 255;
int numBytesToTransfer = Math.min(3, b - keep + 1);
if (numBytesToTransfer < 0) {
numBytesToTransfer = 0;
}

int mask;
for(mask = 8; mask <= 8 * numBytesToTransfer; mask += 8) {
result[i] |= (a[b--] & 255) << mask;
}

mask = -1 >>> 8 * (3 - numBytesToTransfer);
result[i] = ~result[i] & mask;
}

for(i = result.length - 1; i >= 0; --i) {
result[i] = (int)(((long)result[i] & 4294967295L) + 1L);
if (result[i] != 0) {
break;
}
}

return result;
}

private static int[] makePositive(int[] a) {
int keep;
for(keep = 0; keep < a.length && a[keep] == -1; ++keep) {
}

int j;
for(j = keep; j < a.length && a[j] == 0; ++j) {
}

int extraInt = j == a.length ? 1 : 0;
int[] result = new int[a.length - keep + extraInt];

int i;
for(i = keep; i < a.length; ++i) {
result[i - keep + extraInt] = ~a[i];
}

for(i = result.length - 1; ++result[i] == 0; --i) {
}

return result;
}

private int intLength() {
return (this.bitLength() >>> 5) + 1;
}

private int signBit() {
return this.signum < 0 ? 1 : 0;
}

private int signInt() {
return this.signum < 0 ? -1 : 0;
}

private int getInt(int n) {
if (n < 0) {
return 0;
} else if (n >= this.mag.length) {
return this.signInt();
} else {
int magInt = this.mag[this.mag.length - n - 1];
return this.signum >= 0 ? magInt : (n <= this.firstNonzeroIntNum() ? -magInt : ~magInt);
}
}

private int firstNonzeroIntNum() {
int fn = this.firstNonzeroIntNumPlusTwo - 2;
if (fn == -2) {
int mlen = this.mag.length;

int i;
for(i = mlen - 1; i >= 0 && this.mag[i] == 0; --i) {
}

fn = mlen - i - 1;
this.firstNonzeroIntNumPlusTwo = fn + 2;
}

return fn;
}

private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
GetField fields = s.readFields();
int sign = fields.get("signum", -2);
byte[] magnitude = (byte[])fields.get("magnitude", (Object)null);
if (sign >= -1 && sign <= 1) {
int[] mag = stripLeadingZeroBytes(magnitude, 0, magnitude.length);
if (mag.length == 0 != (sign == 0)) {
String message = "BigInteger: signum-magnitude mismatch";
if (fields.defaulted("magnitude")) {
message = "BigInteger: Magnitude not present in stream";
}

throw new StreamCorruptedException(message);
} else {
BigInteger.UnsafeHolder.putSign(this, sign);
BigInteger.UnsafeHolder.putMag(this, mag);
if (mag.length >= 67108864) {
try {
this.checkRange();
} catch (ArithmeticException var7) {
throw new StreamCorruptedException("BigInteger: Out of the supported range");
}
}

}
} else {
String message = "BigInteger: Invalid signum value";
if (fields.defaulted("signum")) {
message = "BigInteger: Signum not present in stream";
}

throw new StreamCorruptedException(message);
}
}

private void writeObject(ObjectOutputStream s) throws IOException {
PutField fields = s.putFields();
fields.put("signum", this.signum);
fields.put("magnitude", this.magSerializedForm());
fields.put("bitCount", -1);
fields.put("bitLength", -1);
fields.put("lowestSetBit", -2);
fields.put("firstNonzeroByteNum", -2);
s.writeFields();
}

private byte[] magSerializedForm() {
int len = this.mag.length;
int bitLen = len == 0 ? 0 : (len - 1 << 5) + bitLengthForInt(this.mag[0]);
int byteLen = bitLen + 7 >>> 3;
byte[] result = new byte[byteLen];
int i = byteLen - 1;
int bytesCopied = 4;
int intIndex = len - 1;

for(int nextInt = 0; i >= 0; --i) {
if (bytesCopied == 4) {
nextInt = this.mag[intIndex--];
bytesCopied = 1;
} else {
nextInt >>>= 8;
++bytesCopied;
}

result[i] = (byte)nextInt;
}

return result;
}

public long longValueExact() {
if (this.mag.length <= 2 && this.bitLength() <= 63) {
return this.longValue();
} else {
throw new ArithmeticException("BigInteger out of long range");
}
}

public int intValueExact() {
if (this.mag.length <= 1 && this.bitLength() <= 31) {
return this.intValue();
} else {
throw new ArithmeticException("BigInteger out of int range");
}
}

public short shortValueExact() {
if (this.mag.length <= 1 && this.bitLength() <= 31) {
int value = this.intValue();
if (value >= -32768 && value <= 32767) {
return this.shortValue();
}
}

throw new ArithmeticException("BigInteger out of short range");
}

public byte byteValueExact() {
if (this.mag.length <= 1 && this.bitLength() <= 31) {
int value = this.intValue();
if (value >= -128 && value <= 127) {
return this.byteValue();
}
}

throw new ArithmeticException("BigInteger out of byte range");
}

static {
int i;
for(i = 1; i <= 16; ++i) {
int[] magnitude = new int[]{i};
posConst[i] = new BigInteger(magnitude, 1);
negConst[i] = new BigInteger(magnitude, -1);
}

powerCache = new BigInteger[37][];
logCache = new double[37];

for(i = 2; i <= 36; ++i) {
powerCache[i] = new BigInteger[]{valueOf((long)i)};
logCache[i] = Math.log((double)i);
}

ZERO = new BigInteger(new int[0], 0);
ONE = valueOf(1L);
TWO = valueOf(2L);
NEGATIVE_ONE = valueOf(-1L);
TEN = valueOf(10L);
bnExpModThreshTable = new int[]{7, 25, 81, 241, 673, 1793, 2147483647};
zeros = new String[64];
zeros[63] = "000000000000000000000000000000000000000000000000000000000000000";

for(i = 0; i < 63; ++i) {
zeros[i] = zeros[63].substring(0, i);
}

digitsPerLong = new int[]{0, 0, 62, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12};
longRadix = new BigInteger[]{null, null, valueOf(4611686018427387904L), valueOf(4052555153018976267L), valueOf(4611686018427387904L), valueOf(7450580596923828125L), valueOf(4738381338321616896L), valueOf(3909821048582988049L), valueOf(1152921504606846976L), valueOf(1350851717672992089L), valueOf(1000000000000000000L), valueOf(5559917313492231481L), valueOf(2218611106740436992L), valueOf(8650415919381337933L), valueOf(2177953337809371136L), valueOf(6568408355712890625L), valueOf(1152921504606846976L), valueOf(2862423051509815793L), valueOf(6746640616477458432L), valueOf(799006685782884121L), valueOf(1638400000000000000L), valueOf(3243919932521508681L), valueOf(6221821273427820544L), valueOf(504036361936467383L), valueOf(876488338465357824L), valueOf(1490116119384765625L), valueOf(2481152873203736576L), valueOf(4052555153018976267L), valueOf(6502111422497947648L), valueOf(353814783205469041L), valueOf(531441000000000000L), valueOf(787662783788549761L), valueOf(1152921504606846976L), valueOf(1667889514952984961L), valueOf(2386420683693101056L), valueOf(3379220508056640625L), valueOf(4738381338321616896L)};
digitsPerInt = new int[]{0, 0, 30, 19, 15, 13, 11, 11, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5};
intRadix = new int[]{0, 0, 1073741824, 1162261467, 1073741824, 1220703125, 362797056, 1977326743, 1073741824, 387420489, 1000000000, 214358881, 429981696, 815730721, 1475789056, 170859375, 268435456, 410338673, 612220032, 893871739, 1280000000, 1801088541, 113379904, 148035889, 191102976, 244140625, 308915776, 387420489, 481890304, 594823321, 729000000, 887503681, 1073741824, 1291467969, 1544804416, 1838265625, 60466176};
serialPersistentFields = new ObjectStreamField[]{new ObjectStreamField("signum", Integer.TYPE), new ObjectStreamField("magnitude", byte[].class), new ObjectStreamField("bitCount", Integer.TYPE), new ObjectStreamField("bitLength", Integer.TYPE), new ObjectStreamField("firstNonzeroByteNum", Integer.TYPE), new ObjectStreamField("lowestSetBit", Integer.TYPE)};
}

private static class UnsafeHolder {
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long signumOffset;
private static final long magOffset;

private UnsafeHolder() {
}

static void putSign(BigInteger bi, int sign) {
unsafe.putInt(bi, signumOffset, sign);
}

static void putMag(BigInteger bi, int[] magnitude) {
unsafe.putObject(bi, magOffset, magnitude);
}

static {
signumOffset = unsafe.objectFieldOffset(BigInteger.class, "signum");
magOffset = unsafe.objectFieldOffset(BigInteger.class, "mag");
}
}
}

Java知识点

Java相关

请问JDK和JRE的区别是什么?

JDK :Java 开发工具包,jdk 是整个 Java 开发的核心,它集成了 jre 和一些好用的小工具。
JRE :Java 运行时环境。它主要包含两个部分,jvm 的标准实现和 Java 的一些基本类库。

springboot的注解有什么,原理?

@Bean
用来代替 XML 配置文件里面的 <bean …> 配置。
@ImportResource
如果有些通过类的注册方式配置不了的,可以通过这个注解引入额外的 XML 配置文件,有些老的配置文件无法通过 @Configuration 方式配置的非常管用。
@Import
用来引入额外的一个或者多个 @Configuration 修饰的配置文件类。
@SpringBootConfiguration
这个注解就是 @Configuration 注解的变体,只是用来修饰是 Spring Boot 配置而已,或者可利于 Spring Boot 后续的扩展,源码如下。
@SpringBootApplication:包含了@ComponentScan、@Configuration和@EnableAutoConfiguration注解。其中@ComponentScan让spring Boot扫描到Configuration类并把它加入到程序上下文。
@Configuration 等同于spring的XML配置文件;使用Java代码可以检查类型安全。
@EnableAutoConfiguration 自动配置。
@ComponentScan 组件扫描,可自动发现和装配一些Bean。
@Component可配合CommandLineRunner使用,在程序启动后执行一些基础任务。
@RestController注解是@Controller和@ResponseBody的合集,表示这是个控制器bean,并且是将函数的返回值直 接填入HTTP响应体中,是REST风格的控制器。
@Autowired自动导入。
@PathVariable获取参数。
@JsonBackReference解决嵌套外链问题。
@RepositoryRestResourcepublic配合spring-boot-starter-data-rest使用。

@RequestMapping:@RequestMapping(“/path”)表示该控制器处理所有“/path”的UR L请求。RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。
用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。该注解有六个属性:
params:指定request中必须包含某些参数值是,才让该方法处理。
headers:指定request中必须包含某些指定的header值,才能让该方法处理请求。
value:指定请求的实际地址,指定的地址可以是URI Template 模式
method:指定请求的method类型, GET、POST、PUT、DELETE等
consumes:指定处理请求的提交内容类型(Content-Type),如application/json,text/html;
produces:指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回

@RequestParam:用在方法的参数前面。
@RequestParam
String a =request.getParameter(“a”)。

@PathVariable:路径变量。如

1
2
3
4
@RequestMapping(“user/get/mac/{macAddress}”) 
public String getByMacAddress(@PathVariable String macAddress){
//do something;
}

Spring Boot的自动配置看起来神奇,其实原理非常简单,背后全依赖于@Conditional注解来实现的。

object类中的hashCode()方法是做什么的,以及其中的hash()方法是做什么的, 为什么有hash()方法还有hashCode()

哈希表这个数据结构想必大多数人都不陌生,而且在很多地方都会利用到hash表来提高查找效率。在Java的Object类中有一个方法:

1
public native int hashCode();

根据这个方法的声明可知,该方法返回一个int类型的数值,并且是本地方法,因此在Object类中并没有给出具体的实现。

hashCode方法的作用

对于包含容器类型的程序设计语言来说,基本上都会涉及到hashCode。在Java中也一样,hashCode方法的主要作用是为了配合基于散列的集合一起正常运行,这样的散列集合包括HashSet、HashMap以及HashTable。

  为什么这么说呢?考虑一种情况,当向集合中插入对象时,如何判别在集合中是否已经存在该对象了?(注意:集合中不允许重复的元素存在)

  也许大多数人都会想到调用equals方法来逐个进行比较,这个方法确实可行。但是如果集合中已经存在一万条数据或者更多的数据,如果采用equals方法去逐一比较,效率必然是一个问题。此时hashCode方法的作用就体现出来了,当集合要添加新的对象时,先调用这个对象的hashCode方法,得到对应的hashcode值,实际上在HashMap的具体实现中会用一个table保存已经存进去的对象的hashcode值,如果table中没有该hashcode值,它就可以直接存进去,不用再进行任何比较了;如果存在该hashcode值, 就调用它的equals方法与新元素进行比较,相同的话就不存了,不相同就散列其它的地址,所以这里存在一个冲突解决的问题,这样一来实际调用equals方法的次数就大大降低了,说通俗一点:Java中的hashCode方法就是根据一定的规则将与对象相关的信息(比如对象的存储地址,对象的字段等)映射成一个数值,这个数值称作为散列值。

hash 算法

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

首先,假设有一种情况,对象 A 的 hashCode 为 1000010001110001000001111000000,对象 B 的 hashCode 为 0111011100111000101000010100000。

如果数组长度是16,也就是 15 与运算这两个数, 你会发现结果都是0。这样的散列结果太让人失望了。很明显不是一个好的散列算法。

但是如果我们将 hashCode 值右移 16 位,也就是取 int 类型的一半,刚好将该二进制数对半切开。并且使用位异或运算(如果两个数对应的位置相反,则结果为1,反之为0),这样的话,就能避免我们上面的情况的发生。

总的来说,使用位移 16 位和 异或 就是防止这种极端情况。但是,该方法在一些极端情况下还是有问题,比如:10000000000000000000000000 和 1000000000100000000000000 这两个数,如果数组长度是16,那么即使右移16位,在异或,hash 值还是会重复。但是为了性能,对这种极端情况,JDK 的作者选择了性能。毕竟这是少数情况,为了这种情况去增加 hash 时间,性价比不高。

hashmap的put过程 主要就是根据自己看过的源码说一下流程

put 方法
通过 hash 计算下标并检查 hash 是否冲突,也就是对应的下标是否已存在元素。

1
2
3
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
  1. 判断数组是否为空,如果是空,则创建默认长度位 16 的数组。
  2. 通过与运算计算对应 hash 值的下标,如果对应下标的位置没有元素,则直接创建一个。
  3. 如果有元素,说明 hash 冲突了,则再次进行 3 种判断。
    1. 判断两个冲突的key是否相等,equals 方法的价值在这里体现了。如果相等,则将已经存在的值赋给变量e。最后更新e的value,也就是替换操作。
    2. 如果key不相等,则判断是否是红黑树类型,如果是红黑树,则交给红黑树追加此元素。
    3. 如果key既不相等,也不是红黑树,则是链表,那么就遍历链表中的每一个key和给定的key是否相等。如果,链表的长度大于等于8了,则将链表改为红黑树,这是Java8 的一个新的优化。
  4. 最后,如果这三个判断返回的 e 不为null,则说明key重复,则更新key对应的value的值。
  5. 对维护着迭代器的modCount 变量加一。
  6. 最后判断,如果当前数组的长度已经大于阀值了。则重新hash。

ArrayList LinkList的特点

ArrayList是实现了基于动态数组的结构,LinkedList则是基于实现链表的数据结构。

数据的更新和查找
ArrayList的所有数据是在同一个地址上,而LinkedList的每个数据都拥有自己的地址.所以在对数据进行查找的时候,由于LinkedList的每个数据地址不一样,get数据的时候ArrayList的速度会优于LinkedList,而更新数据的时候,虽然都是通过循环循环到指定节点修改数据,但LinkedList的查询速度已经是慢的,而且对于LinkedList而言,更新数据时不像ArrayList只需要找到对应下标更新就好,LinkedList需要修改指针,速率不言而喻

数据的增加和删除
对于数据的增加元素,ArrayList是通过移动该元素之后的元素位置,其后元素位置全部+1,所以耗时较长,而LinkedList只需要将该元素前的后续指针指向该元素并将该元素的后续指针指向之后的元素即可。与增加相同,删除元素时ArrayList需要将被删除元素之后的元素位置-1,而LinkedList只需要将之后的元素前置指针指向前一元素,前一元素的指针指向后一元素即可。当然,事实上,若是单一元素的增删,尤其是在List末端增删一个元素,二者效率不相上下。

红黑树定义

红黑树本质上是一种二叉查找树,但它在二叉查找树的基础上额外添加了一个标记(颜色),同时具有一定的规则。这些规则使红黑树保证了一种平衡,插入、删除、查找的最坏时间复杂度都为 O(logn)。

它的统计性能要好于平衡二叉树(AVL树),因此,红黑树在很多地方都有应用。比如在 Java 集合框架中,很多部分(HashMap, TreeMap, TreeSet 等)都有红黑树的应用,这些集合均提供了很好的性能。

由于 TreeMap 就是由红黑树实现的。

黑色高度
从根节点到叶节点的路径上黑色节点的个数,叫做树的黑色高度。

  1. 每个节点要么是红色,要么是黑色;
  2. 根节点永远是黑色的;
  3. 所有的叶节点都是是黑色的(注意这里说叶子节点其实是上图中的 NIL 节点);
  4. 每个红色节点的两个子节点一定都是黑色;
  5. 从任一节点到其子树中每个叶子节点的路径都包含相同数量的黑色节点;

Java 反射机制

Java 反射机制在程序运行时,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性。这种 动态的获取信息 以及 动态调用对象的方法 的功能称为 java 的反射机制。

1
2
3
4
5
6
public class FatherClass {
public String mFatherName;
public int mFatherAge;

public void printFatherMsg(){}
}

多线程相关

synchronized

synchronized 是 Java 中的关键字,是利用锁的机制来实现同步的。

锁机制有如下两种特性:

  • 互斥性:即在同一时间只允许一个线程持有某个对象锁,通过这种特性来实现多线程中的协调机制,这样在同一时间只有一个线程对需同步的代码块(复合操作)进行访问。互斥性我们也往往称为操作的原子性。

  • 可见性:必须确保在锁被释放之前,对共享变量所做的修改,对于随后获得该锁的另一个线程是可见的(即在获得锁时应获得最新共享变量的值),否则另一个线程可能是在本地缓存的某个副本上继续操作从而引起不一致。

synchronized 可以修饰方法和代码块

  • synchronized(this|object) {}
  • synchronized(类.class) {}
  • 修饰非静态方法
  • 修饰静态方法

reentrantLock 除了可重入还有什么关键特性

  • 可重入

现在有方法 m1 和 m2,两个方法均使用了同一把锁对方法进行同步控制,同时方法 m1 会调用 m2。线程 t 进入方法 m1 成功获得了锁,此时线程 t 要在没有释放锁的情况下,调用 m2 方法。由于 m1 和 m2 使用的是同一把可重入锁,所以线程 t 可以进入方法 m2,并再次获得锁,而不会被阻塞住。

  • 公平和非公平锁

公平与非公平指的是线程获取锁的方式。公平模式下,线程在同步队列中通过 FIFO 的方式获取锁,每个线程最终都能获取锁。在非公平模式下,线程会通过“插队”的方式去抢占锁,抢不到的则进入同步队列进行排队。默认情况下,ReentrantLock 使用的是非公平模式获取锁,而不是公平模式。不过我们也可通过 ReentrantLock 构造方法ReentrantLock(boolean fair)调整加锁的模式。

ThreadLocal 会造成什么问题? 为什么会造成内存泄漏?

  • ThreadLocal类用来提供线程内部的局部变量。这些变量在多线程环境下访问(通过get或set方法访问)时能保证各个线程里的变量相对独立于其他线程内的变量,ThreadLocal实例通常来说都是private static类型。 总结:ThreadLocal不是为了解决多线程访问共享变量,而是为每个线程创建一个单独的变量副本,提供了保持对象的方法和避免参数传递的复杂性。
  • ThreadLocal的主要应用场景为按线程多实例(每个线程对应一个实例)的对象的访问,并且这个对象很多地方都要用到。例如:同一个网站登录用户,每个用户服务器会为其开一个线程,每个线程中创建一个ThreadLocal,里面存用户基本信息等,在很多页面跳转时,会显示用户信息或者得到用户的一些信息等频繁操作,这样多线程之间并没有联系而且当前线程也可以及时获取想要的数据。

ThreadLocal类提供了四个对外开放的接口方法

(1) void set(Object value)设置当前线程的线程局部变量的值。
(2) public Object get()该方法返回当前线程所对应的线程局部变量。
(3) public void remove()将当前线程局部变量的值删除,目的是为了减少内存的占用。
(4) protected Object initialValue()返回该线程局部变量的初始值。

在threadLocal设为null和线程结束这段时间不会被回收的,就发生了我们认为的内存泄露。其实这是一个对概念理解的不一致,也没什么好争论的。

最要命的是线程对象不被回收的情况,这就发生了真正意义上的内存泄露。比如使用线程池的时候,线程结束是不会销毁的,会再次使用的就可能出现内存泄露。(在web应用中,每次http请求都是一个线程,tomcat容器配置使用线程池时会出现内存泄漏问题)

  1. 使用ThreadLocal,建议用static修饰 static ThreadLocal headerLocal = new ThreadLocal();
  2. 使用完ThreadLocal后,执行remove操作,避免出现内存溢出情况。

单例模式 synchronized实现懒汉模式?为什么用内部类是线程安全的?

内部类

单例模式,有“懒汉式”和“饿汉式”两种。
懒汉式
单例类的实例在第一次被引用时候才被初始化。
饿汉式
单例类的实例在加载的时候就被初始化。

静态内部类模式

1
2
3
4
5
6
7
8
9
10
public class Singleton { 
private Singleton(){
}
public static Singleton getSingleton(){
return Inner.instance;
}
private static class Inner {
private static final Singleton instance = new Singleton();
}
}
  1. 实现代码简洁。和双重检查单例对比,静态内部类单例实现代码真的是太简洁,又清晰明了。
  2. 延迟初始化。调用getSingleton才初始化Singleton对象。
  3. 线程安全。JVM在执行类的初始化阶段,会获得一个可以同步多个线程对同一个类的初始化的锁。

线程A和线程B同时试图获得Singleton对象的初始化锁,假设线程A获取到了,那么线程B一直等待初始化锁。线程A执行类初始化,就算双重检查模式中伪代码发生了重排序,