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执行类初始化,就算双重检查模式中伪代码发生了重排序,也不会影响线程A的初始化结果。初始化完后,释放锁。线程B获得初始化锁,发现Singleton对象已经初始化完毕,释放锁,不进行初始化,获得Singleton对象。

数据库相关

添加索引的时候要注意什么

索引可以提高数据的访问速度,但同时也增加了插入、更新和删除操作的处理时间。所以是否要为表增加索引、索引建立在那些字段上,是创建索引前必须要考虑的问题。解决此问题就是分析应用程序的业务处理、数据使用,为经常被用作查询条件、或者被要求排序的字段建立索引。

1、表的主键、外键必须有索引;
2、数据量超过300的表应该有索引;
3、经常与其他表进行连接的表,在连接字段上应该建立索引;
4、经常出现在Where子句中的字段,特别是大表的字段,应该建立索引;
5、索引应该建在选择性高的字段上;
6、索引应该建在小字段上,对于大的文本字段甚至超长字段,不要建索引;
7、复合索引的建立需要进行仔细分析;

聚簇索引:
通常由主键或者非空唯一索引实现的,叶子节点存储了一整行数据
非聚簇索引:
又称二级索引,就是我们常用的普通索引,叶子节点存了索引值和主键值,在根据主键从聚簇索引查

索引优化以及在使用索引的时候要注意什么

1.索引列不要使用函数和运算

  1. 尽量避免使用 != 或 not in或 <> 等否定操作符
  2. 当查询条件为多个的时候,可以采用复合索引
  3. 范围查询对多列查询的影响
  4. 遵循最左匹配原则
    复合索引遵守“最左前缀”原则,即在查询条件中使用了复合索引的第一个字段,索引才会被使用。因此,在复合索引中索引列的顺序至关重要。如果不是按照索引的最左列开始查找,则无法使用索引。
  5. 索引列不会包含NULL值
  6. 尽量避免使用 or 来连接条件
  7. 隐式转换的影响
  8. like 语句的索引失效问题

redis的键的淘汰策略,会达成了redis缓存的淘汰策略

Redis作为一个高性能的内存NoSQL数据库,其容量受到最大内存限制的限制。
事实上,实例中的内存除了保存原始的键值对所需的开销外,还有一些运行时产生的额外内存,包括:

  1. 垃圾数据和过期Key所占空间
  2. 字典渐进式Rehash导致未及时删除的空间
  3. Redis管理数据,包括底层数据结构开销,客户端信息,读写缓冲区等
  4. 主从复制,bgsave时的额外开销

为了防止一次性清理大量过期Key导致Redis服务受影响,Redis只在空闲时清理过期Key。

  • 访问Key时,会判断Key是否过期,逐出过期Key;
  • CPU空闲时在定期serverCron任务中,逐出部分过期Key;
  • 每次事件循环执行的时候,逐出部分过期Key;

网络相关

tcp四次握手,最后的状态是什么?

等待2MSL的时间?(MSL最长报文段寿命Maximum Segment Lifetime,MSL=2)

为什么要等着2MSL,等待多了会造成什么

  1. 保证A发送的最后一个ACK报文段能够到达B。
  2. 防止“已失效的连接请求报文段”出现在本连接中。A在发送完最后一个ACK报文段后,再经过2MSL,就可以使本连接持续的时间内所产生的所有报文段都从网络中消失,使下一个新的连接中不会出现这种旧的连接请求报文段。

http请求的报文结构,keep-alive是用来做什么的

当使用Keep-Alive模式(又称持久连接、连接重用)时,Keep-Alive功能使客户端到服 务器端的连接持续有效,当出现对服务器的后继请求时,Keep-Alive功能避免了建立或者重新建立连接。

1
2
Keep-Alive: timeout=5, max=100
timeout:过期时间5秒(对应httpd.conf里的参数是:KeepAliveTimeout),max是最多一百次请求,强制断掉连接

spring spingboot

spring为什么要注入接口,而不是实现类

首先说明,注入的对象确实为实现类的对象。(并不是实现类的代理对象,注入并不涉及代理)

  如果只是单纯注入是可以用实现类接收注入对象的,但是往往开发中会对实现类做增强,如事务,日志等,实现增强的AOP技术是通过动态代理实现的,而spring默认是JDK动态代理,对实现类对象做增强得到的增强类与实现类是兄弟关系,所以不能用实现类接收增强类对象,只能用接口接收。

回答没听过这个概念,然后被引导回到IOC和AOP,以及AOP是什么,实现过程

Java动态代理为我们提供了非常灵活的代理机制,但Java动态代理是基于接口的,如果目标对象没有实现接口我们该如何代理呢?这时候我们就需要使用CGLIB来实现AOP了。

假如我们要使用动态代理实现AOP,那么我们只能在写一个增强的接口,然后让目标类实现增强接口,然后我们就可以使用动态代理实现目标类的增强,可是假如我们不想让目标类实现其他的接口,那么我们就只能使用CGLIB技术来实现目标类的增强了。
CGLIB实现目标类增强的原理是这样的:CGLIB会动态创建一个目标类的子类,然后返回该子类的对象,也就是增强对象,至于增强的逻辑则是在子类中完成的。我们知道子类要么和父类有一样的功能,要么就比父类功能强大,所以CGLIB是通过创建目标类的子类对象来实现增强的,所以:

1
目标子类 = 目标类 + 增强逻辑

口述算法思路

给一个栈的数据结构,实现另外一个数据结构,要求保留栈的特性,同时能够提供去最大值和最小值的方法,时间复杂度为O(1)

最小值思路:用一个辅助栈stack2记住每次入栈stack1的当前最小值:在stack1入栈时,往stack2中加入当前最小值;stack1元素出栈时,stack2也出栈一个元素。最小值从stack2中获取及栈顶元素。O(1)

最大值思路:同上O(1)

image.png

网络编程

哪几种IO类型

  • 阻塞I/O(blocking IO)
  • 非阻塞I/O (nonblocking I/O)
  • I/O 复用 (I/O multiplexing)
  • 信号驱动I/O (signal driven I/O (SIGIO))
  • 异步I/O (asynchronous I/O)

JVM

JVM的内存结构

  • 堆(Heap):线程共享。所有的对象实例以及数组都要在堆上分配。回收器主要管理的对象。
  • 方法区(Method Area):线程共享。存储类信息、常量、静态变量、即时编译器编译后的代码。
  • 方法栈(JVM Stack):线程私有。存储局部变量表、操作栈、动态链接、方法出口,对象指针。
  • 本地方法栈(Native Method Stack):线程私有。为虚拟机使用到的Native 方法服务。如Java使用c或者c++编写的接口服务时,代码在此区运行。
  • 程序计数器(Program Counter Register):线程私有。有些文章也翻译成PC寄存器(PC Register),同一个东西。它可以看作是当前线程所执行的字节码的行号指示器。指向下一条要执行的指令。

image.png

类加载机制

Java虚拟机把描述类的数据从Class文件加载到内存,并对数据进行校验、转换解析和初始化,最终形成可以被虚拟机直接使用的Java类型,这就是虚拟机的加载机制。*
Class文件由类装载器装载后,在JVM中将形成一份描述Class结构的元信息对象,通过该元信息对象可以获知Class的结构信息:如构造函数,属性和方法等,Java允许用户借由这个Class相关的元信息对象间接调用Class对象的功能,这里就是我们经常能见到的Class类。

image.png

双亲委派模型

双亲委派的意思是如果一个类加载器需要加载类,那么首先它会把这个类请求委派给父类加载器去完成,每一层都是如此。一直递归到顶层,当父加载器无法完成这个请求时,子类才会尝试去加载。这里的双亲其实就指的是父类,没有mother。父类也不是我们平日所说的那种继承关系,只是调用逻辑是这样。

双亲委派模型不是一种强制性约束,也就是你不这么做也不会报错怎样的,它是一种JAVA设计者推荐使用类加载器的方式。

有什么想问我的

有的

  1. 你怎样形容小米公司的企业文化?
  2. 什么类型的员工能在小米公司有比较好的发展?
  3. 关于软件开发工程师-Java方向岗位的技术栈、日常主要工作是什么、期间可以获得晋升机会?
  4. 能给我多讲讲招聘程序吗?
  5. 我没有其他问题了,与您交流非常愉快,能留一张您的名片么?(或者方便加一下您的微信么?)

Java12的新特性

Java12的新特性

Java5的新特性
Java6的新特性
Java7的新特性
Java8的新特性
Java9的新特性
Java10的新特性
Java11的新特性
Java12的新特性
Java13的新特性

image.png

版本号

1
2
3
4
java -version
openjdk version "12" 2019-03-19
OpenJDK Runtime Environment (build 12+33)
OpenJDK 64-Bit Server VM (build 12+33, mixed mode)

从version信息可以看出是build 12+33

特性列表

Shenandoah GC是一个面向low-pause-time的垃圾收集器,它最初由Red Hat实现,支持aarch64及amd64 architecture;ZGC也是面向low-pause-time的垃圾收集器,不过ZGC是基于colored pointers来实现,而Shenandoah GC是基于brooks pointers来实现;如果要使用Shenandoah GC需要编译时–with-jvm-features选项带有shenandoahgc,然后启动时使用-XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC

在jdk源码里头新增了一套基础的microbenchmarks suite

对switch进行了增强,除了使用statement还可以使用expression,比如原来的写法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
switch (day) {
case MONDAY:
case FRIDAY:
case SUNDAY:
System.out.println(6);
break;
case TUESDAY:
System.out.println(7);
break;
case THURSDAY:
case SATURDAY:
System.out.println(8);
break;
case WEDNESDAY:
System.out.println(9);
break;
}

现在可以改为如下写法:

1
2
3
4
5
6
switch (day) {
case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);
case TUESDAY -> System.out.println(7);
case THURSDAY, SATURDAY -> System.out.println(8);
case WEDNESDAY -> System.out.println(9);
}

以及在表达式返回值

1
2
3
4
5
6
int numLetters = switch (day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case THURSDAY, SATURDAY -> 8;
case WEDNESDAY -> 9;
};

对于需要返回值的switch expression要么正常返回值要么抛出异常,以下这两种写法都是错误的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int i = switch (day) {
case MONDAY -> {
System.out.println("Monday");
// ERROR! Block doesn't contain a break with value
}
default -> 1;
};
i = switch (day) {
case MONDAY, TUESDAY, WEDNESDAY:
break 0;
default:
System.out.println("Second half of the week");
// ERROR! Group doesn't contain a break with value
};

新增了JVM Constants API,具体来说就是java.base模块新增了java.lang.constant包,引入了ConstantDesc接口(ClassDesc、MethodTypeDesc、MethodHandleDesc这几个接口直接继承了ConstantDesc接口)以及Constable接口;ConstantDesc接口定义了resolveConstantDesc方法,Constable接口定义了describeConstable方法;String、Integer、Long、Float、Double均实现了这两个接口,而EnumDesc实现了ConstantDesc接口

64-bit Arm platform (arm64),也可以称之为aarch64;之前JDK有两个关于aarch64的实现,分别是src/hotspot/cpu/arm以及open/src/hotspot/cpu/aarch64,它们的实现重复了,为了集中精力更好地实现aarch64,该特性在源码中删除了open/src/hotspot/cpu/arm中关于64-bit的实现,保留其中32-bit的实现,于是open/src/hotspot/cpu/aarch64部分就成了64-bit ARM architecture的默认实现

java10的新特性JEP 310: Application Class-Data Sharing扩展了JDK5引入的Class-Data Sharing,支持application的Class-Data Sharing;Class-Data Sharing可以用于多个JVM共享class,提升启动速度,最早只支持system classes及serial GC,JDK9对其进行扩展以支持application classes及其他GC算法,并在JDK10中开源出来(以前是commercial feature);JDK11将-Xshare:off改为默认-Xshare:auto,以更加方便使用CDS特性;JDK12的这个特性即在64-bit平台上编译jdk的时候就默认在${JAVA_HOME}/lib/server目录下生成一份名为classes.jsa的默认archive文件(大概有18M)方便大家使用

G1在garbage collection的时候,一旦确定了collection set(CSet)开始垃圾收集这个过程是without stopping的,当collection set过大的时候,此时的STW时间会过长超出目标pause time,这种情况在mixed collections时候比较明显。这个特性启动了一个机制,当选择了一个比较大的collection set,允许将其分为mandatory及optional两部分(当完成mandatory的部分,如果还有剩余时间则会去处理optional部分)来将mixed collections从without stopping变为abortable,以更好满足指定pause time的目标

G1目前只有在full GC或者concurrent cycle的时候才会归还内存,由于这两个场景都是G1极力避免的,因此在大多数场景下可能不会及时会还committed Java heap memory给操作系统。JDK12的这个特性新增了两个参数分别是G1PeriodicGCInterval及G1PeriodicGCSystemLoadThreshold,设置为0的话,表示禁用。当上一次garbage collection pause过去G1PeriodicGCInterval(milliseconds)时间之后,如果getloadavg()(one-minute)低于G1PeriodicGCSystemLoadThreshold指定的阈值,则触发full GC或者concurrent GC(如果开启G1PeriodicGCInvokesConcurrent),GC之后Java heap size会被重写调整,然后多余的内存将会归还给操作系统

细项解读

上面列出的是大方面的特性,除此之外还有一些api的更新及废弃,主要见JDK 12 Release Notes,这里举几个例子。
添加项

  • 支持unicode 11
  • 支持Compact Number Formatting

使用实例如下

1
2
3
4
5
6
7
8
9
10
@Test
public void testCompactNumberFormat(){
var cnf = NumberFormat.getCompactNumberInstance(Locale.CHINA, NumberFormat.Style.SHORT);
System.out.println(cnf.format(1_0000));
System.out.println(cnf.format(1_9200));
System.out.println(cnf.format(1_000_000));
System.out.println(cnf.format(1L << 30));
System.out.println(cnf.format(1L << 40));
System.out.println(cnf.format(1L << 50));
}

输出

1
2
3
4
5
6
1万
2万
100万
11亿
1兆
1126兆
  • String支持transform、indent操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
public void testStringTransform(){
System.out.println("hello".transform(new Function<String, Integer>() {
@Override
public Integer apply(String s) {
return s.hashCode();
}
}));
}

@Test
public void testStringIndent(){
System.out.println("hello".indent(3));
}

Files新增mismatch方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
public void testFilesMismatch() throws IOException {
FileWriter fileWriter = new FileWriter("/tmp/a.txt");
fileWriter.write("a");
fileWriter.write("b");
fileWriter.write("c");
fileWriter.close();

FileWriter fileWriterB = new FileWriter("/tmp/b.txt");
fileWriterB.write("a");
fileWriterB.write("1");
fileWriterB.write("c");
fileWriterB.close();

System.out.println(Files.mismatch(Path.of("/tmp/a.txt"),Path.of("/tmp/b.txt")));
}
  • Collectors新增teeing方法用于聚合两个downstream的结果
1
2
3
4
5
6
7
8
9
10
11
@Test
public void testCollectorTeeing(){
var result = Stream.of("Devoxx","Voxxed Days","Code One","Basel One")
.collect(Collectors.teeing(Collectors.filtering(n -> n.contains("xx"),Collectors.toList()),
Collectors.filtering(n -> n.endsWith("One"),Collectors.toList()),
(List<String> list1, List<String> list2) -> List.of(list1,list2)
));

System.out.println(result.get(0));
System.out.println(result.get(1));
}
  • CompletionStage新增exceptionallyAsync、exceptionallyCompose、exceptionallyComposeAsync方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
public void testExceptionallyAsync() throws ExecutionException, InterruptedException {
LOGGER.info("begin");
int result = CompletableFuture.supplyAsync(() -> {
LOGGER.info("calculate");
int i = 1/0;
return 100;
}).exceptionallyAsync((t) -> {
LOGGER.info("error error:{}",t.getMessage());
return 0;
}).get();

LOGGER.info("result:{}",result);
}
  • JDK12之前CompletionStage只有一个exceptionally,该方法体在主线程执行,JDK12新增了exceptionallyAsync、exceptionallyComposeAsync方法允许方法体在异步线程执行,同时新增了exceptionallyCompose方法支持在exceptionally的时候构建新的CompletionStage

  • Allocation of Old Generation of Java Heap on Alternate Memory Devices

G1及Parallel GC引入experimental特性,允许将old generation分配在诸如NV-DIMM memory的alternative memory device

  • ZGC: Concurrent Class Unloading

ZGC在JDK11的时候还不支持class unloading,JDK12对ZGC支持了Concurrent Class Unloading,默认是开启,使用-XX:-ClassUnloading可以禁用

  • 新增-XX:+ExtensiveErrorReports

-XX:+ExtensiveErrorReports可以用于在jvm crash的时候收集更多的报告信息到hs_err.log文件中,product builds中默认是关闭的,要开启的话,需要自己添加-XX:+ExtensiveErrorReports参数

  • 新增安全相关的改进

支持java.security.manager系统属性,当设置为disallow的时候,则不使用SecurityManager以提升性能,如果此时调用System.setSecurityManager则会抛出UnsupportedOperationException
keytool新增-groupname选项允许在生成key pair的时候指定一个named group
新增PKCS12 KeyStore配置属性用于自定义PKCS12 keystores的生成
Java Flight Recorder新增了security-related的event
支持ChaCha20 and Poly1305 TLS Cipher Suites

  • jdeps Reports Transitive Dependences

jdeps的–print-module-deps, –list-deps, 以及–list-reduce-deps选项得到增强,新增–no-recursive用于non-transitive的依赖分析,–ignore-missing-deps用于suppress missing dependence errors

移除项

  • 移除com.sun.awt.SecurityWarnin
  • 移除FileInputStream、FileOutputStream、Java.util.ZipFile/Inflator/Deflator的finalize方法
  • 移除GTE CyberTrust Global Root
  • 移除javac的-source, -target对6及1.6的支持,同时移除–release选项

废弃项

  • 废弃的API列表见deprecated-list
  • 废弃-XX:+/-MonitorInUseLists选项
  • 废弃Default Keytool的-keyalg值

已知问题

  • Swing不支持GTK+ 3.20及以后的版本
  • 在使用JVMCI Compiler(比如Graal)的时候,JVMTI的can_pop_frame及can_force_early_return的capabilities是被禁用的

其他事项

  • 如果用户没有指定user.timezone且从操作系统获取的为空,那么user.timezone属性的初始值为空变为null
  • java.net.URLPermission的行为发生轻微变化,以前它会忽略url中的query及fragment部分,这次改动新增query及fragment部分,即scheme : // authority [ / path ]变动为scheme : // authority [ / path ] [ ignored-query-or-fragment ]
  • javax.net.ssl.SSLContext API及Java Security Standard Algorithm Names规范移除了必须实现TLSv1及TLSv1.1的规定

小结

  • java12不是LTS(Long-Term Support)版本(oracle版本才有LTS),oracle对该版本的support周期为6个月。这个版本主要有几个更新点,一个是语法层更新,一个是API层面的更新,另外主要是GC方面的更新。
  • 语法层面引入了preview版本的Switch Expressions;API层面引入了JVM Constants API,引入CompactNumberFormat,让NumberFormat支持COMPACTSTYLE,对String、Files、Collectors、CompletionStage等新增方法;GC方面引入了experimental版本的Shenandoah GC,不过oracle build的openjdk没有enable Shenandoah GC support;另外主要对ZGC及G1 GC进行了改进
  • 其中JDK12对ZGC支持了Concurrent Class Unloading,默认是开启,使用-XX:-ClassUnloading可以禁用;对于G1 GC则新增支持Abortable Mixed Collections以及Promptly Return Unused Committed Memory特性

作者:go4it
链接:https://juejin.im/post/5c91fcc9e51d45563b62382c
来源:掘金

Java面试题

基础与框架

String类能被继承吗,为什么?

不可以,因为String类有final修饰符,而final修饰的类是不能被继承的,实现细节不允许改变。

1
public final class String implements java.io.Serializable, Comparable<String>, CharSequence

根据程序上下文环境,Java关键字final有“这是无法改变的”或者“终态的”含义,它可以修饰非抽象类、非抽象类成员方法和变量。你可能出于两种理解而需要阻止改变:设计或效率。
  final类不能被继承,没有子类,final类中的方法默认是final的。
  final方法不能被子类的方法覆盖,但可以被继承。
  final成员变量表示常量,只能被赋值一次,赋值后值不再改变。
  final不能用于修饰构造方法。
  注意:父类的private成员方法是不能被子类方法覆盖的,因此private类型的方法默认是final类型的。

如果一个类不允许其子类覆盖某个方法,则可以把这个方法声明为final方法。
  使用final方法的原因有二:
  第一、把方法锁定,防止任何继承类修改它的意义和实现。
  第二、高效。编译器在遇到调用final方法时候会转入内嵌机制,大大提高执行效率。(这点有待商榷,《Java编程思想》中对于这点存疑)

下面这段话摘自《Java编程思想》第四版第143页:
“使用final方法的原因有两个。第一个原因是把方法锁定,以防任何继承类修改它的含义;第二个原因是效率。在早期的Java实现版本中,会将final方法转为内嵌调用。但是如果方法过于庞大,可能看不到内嵌调用带来的任何性能提升。在最近的Java版本中,不需要使用final方法进行这些优化了。”

关于String类,要了解常量池的概念

1
String s = new String(“xyz”);  //创建了几个对象

答案: 1个或2个, 如果”xyz”已经存在于常量池中,则只在堆中创建”xyz”对象的一个拷贝,否则还要在常量池中在创建一份

1
String s = "a"+"b"+"c"+"d"; //创建了几个对象

答案: 这个和JVM实现有关, 如果常量池为空,可能是1个也可能是7个等

String,Stringbuffer,StringBuilder的区别?

1、用来处理字符串常用的类有3种:String、StringBuffer和StringBuilder
2、三者之间的区别:
都是final类,都不允许被继承;
String类长度是不可变的,StringBuffer和StringBuilder类长度是可以改变的;
StringBuffer类是线程安全的,StringBuilder不是线程安全的;

String 和 StringBuffer:
1、String类型和StringBuffer类型的主要性能区别:String是不可变的对象,因此每次在对String类进行改变的时候都会生成一个新的string对象,然后将指针指向新的string对象,所以经常要改变字符串长度的话不要使用string,因为每次生成对象都会对系统性能产生影响,特别是当内存中引用的对象多了以后,JVM的GC就会开始工作,性能就会降低;

2、使用StringBuffer类时,每次都会对StringBuffer对象本身进行操作,而不是生成新的对象并改变对象引用,所以多数情况下推荐使用StringBuffer,特别是字符串对象经常要改变的情况;

3、在某些情况下,String对象的字符串拼接其实是被Java Compiler编译成了StringBuffer对象的拼接,所以这些时候String对象的速度并不会比StringBuffer对象慢,例如:

1
2
String s1 = “This is only a” + “ simple” + “ test”;
StringBuffer Sb = new StringBuilder(“This is only a”).append(“ simple”).append(“ test”);

生成 String s1对象的速度并不比 StringBuffer慢。其实在Java Compiler里,自动做了如下转换:

1
2
3
4
5
Java Compiler直接把上述第一条语句编译为:
String s2 = “This is only a”;
String s3 = “ simple”;
String s4 = “ test”;
String s1 = s2 + s3 + s4;

传送门

ArrayList和LinkedList有什么区别

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

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

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

传送门

类的实例化顺序,比如父类静态数据,构造函数,字段,子类静态数据,构造函数,字段,他们的执行顺序

此题考察的是类加载器实例化时进行的操作步骤(加载–>连接->初始化)。
父类静态变量、
父类静态代码块、
子类静态变量、
子类静态代码块、
父类非静态变量(父类实例成员变量)、
父类构造函数、
子类非静态变量(子类实例成员变量)、
子类构造函数。

传送门

用过哪些Map,都有什么区别,HashMap是线程安全的吗,并发下使用的Map是什么,他们内部原理分别是什么,比如hashcode,扩容等

Hashtable,HashMap,ConcurrentHashMap

线程不安全的HashMap
因为多线程环境下,使用Hashmap进行put操作会引起死循环,导致CPU利用率接近100%,所以在并发情况下不能使用HashMap。

HashMap
HashMap内部实现是一个桶数组,每个桶中存放着一个单链表的头结点。其中每个结点存储的是一个键值对整体(Entry),HashMap采用拉链法解决哈希冲突

传送门

效率低下的HashTable容器
HashTable容器使用synchronized来保证线程安全,但在线程竞争激烈的情况下HashTable的效率非常低下。因为当一个线程访问HashTable的同步方法时,其他线程访问HashTable的同步方法时,可能会进入阻塞或轮询状态。如线程1使用put进行添加元素,线程2不但不能使用put方法添加元素,并且也不能使用get方法来获取元素,所以竞争越激烈效率越低。

ConcurrentHashMap的锁分段技术
HashTable容器在竞争激烈的并发环境下表现出效率低下的原因,是因为所有访问HashTable的线程都必须竞争同一把锁,那假如容器里有多把锁,每一把锁用于锁容器其中一部分数据,那么当多线程访问容器里不同数据段的数据时,线程间就不会存在锁竞争,从而可以有效的提高并发访问效率,这就是ConcurrentHashMap所使用的锁分段技术,首先将数据分成一段一段的存储,然后给每一段数据配一把锁,当一个线程占用锁访问其中一个段数据的时候,其他段的数据也能被其他线程访问。

传送门

hashcode() 方法,在object类中定义如下:

1
public native int hashCode();

native说明是一个本地方法,它的实现是根据本地机器相关的。当然我们可以在自己写的类中覆盖hashcode()方法,比如String、Integer、Double。。。。等等这些类都是覆盖了hashcode()方法的
例如String类中:就是以31为权,每一位为字符的ASCII值进行运算,用自然溢出来等效取模。(为什么取31?主要是因为31是一个奇质数,所以31i=32i-i=(i<<5)-i,这种位移与减法结合的计算相比一般的运算快很多).

1
2
3
4
5
6
7
8
9
10
11
12
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;

for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}

HashMap为什么get和set那么快,concurrentHashMap为什么能提高并发

HashMap 底层是基于 数组 + 链表 组成的

传送门

抽象类和接口的区别,类可以继承多个类么,接口可以继承多个接口么,类可以实现多个接口么

实现 抽象类使用extends关键字来继承抽象类。如果子类不是抽象类的话,它需要提供抽象类中所有声明的方法的实现。子类使用关键字implements来实现接口。它需要提供接口中所有声明的方法的实现。
抽象类和接口的区别

由于Java不支持多继承,子类不能够继承多个类,但可以实现多个接口。因此你就可以使用接口来解决它。

接口可以继承多个接口。
java类是单继承的。classB Extends classA
java接口可以多继承。Interface3 Extends Interface0, Interface1, interface……
不允许类多重继承的主要原因是,如果A同时继承B和C,而B和C同时有一个D方法,A如何决定该继承那一个呢?
但接口不存在这样的问题,接口全都是抽象方法继承谁都无所谓,所以接口可以继承多个接口。

什么情况下会发生栈内存溢出

方法递归调用产生这种结果

栈是线程私有的,他的生命周期与线程相同,每个方法在执行的时候都会创建一个栈帧,用来存储局部变量表,操作数栈,动态链接,方法出口灯信息。局部变量表又包含基本数据类型,对象引用类型(局部变量表编译器完成,运行期间不会变化)

所以我们可以理解为栈溢出就是方法执行是创建的栈帧超过了栈的深度。那么最有可能的就是方法递归调用产生这种结果。栈溢出(StackOverflowError)

什么是nio,原理

NIO是为了弥补传统I/O工作模式的不足而研发的,NIO的工具包提出了基于Selector(选择器)、Buffer(缓冲区)、Channel(通道)的新模式;Selector(选择器)、可选择的Channel(通道)和SelectionKey(选择键)配合起来使用,可以实现并发的非阻塞型I/O能力。

NIO的工作原理是什么?

  在并发型服务器程序中使用NIO,实际上是通过网络事件驱动模型实现的。我们应用Select机制,不用为每一个客户端连接新启线程处理,而是将其注册到特定的Selector对象上,这就可以在单线程中利用Selector对象管理大量并发的网络连接,更好的利用了系统资源;采用非阻塞I/O的通信方式,不要求阻塞等待I/O操作完成即可返回,从而减少了管理I/O连接导致的系统开销,大幅度提高了系统性能。

  当有读或写等注册事件发生时,可以从Selector中获得相应的SelectionKey,从SelectionKey中可以找到发生的事件和该事件所发生的具体的SelectableChannel,以获得客户端发送过来的数据。由于在非阻塞网络I/O中采用了事件触发机制,处理程序可以得到系统的主动通知,从而可以实现底层网络I/O无阻塞、流畅地读写,而不像在原来的阻塞模式下处理程序需要不断循环等待。使用NIO,可以编写出性能更好、更易扩展的并发型服务器程序。

  并发型服务器程序的实现代码:应用NIO工具包,基于非阻塞网络I/O设计的并发型服务器程序与以往基于阻塞I/O的实现程序有很大不同,在使用非阻塞网络I/O的情况下,程序读取数据和写入数据的时机不是由程序员控制的,而是Selector决定的。

  使用非阻塞型I/O进行并发型服务器程序设计分三个部分:1. 向Selector对象注册感兴趣的事件;2.从Selector中获取所感兴趣的事件;3. 根据不同的事件进行相应的处理。

  在进行并发型服务器程序设计时,通过合理地使用NIO工具包,就可以达到一个或者几个Socket线程就可以处理N多个Socket的连接,大大降低我们对服务器程序的预算压力。同时我们利用它更好地提高系统的性能,使我们的工作得到更加有效地开展。

传送门

反射中,Class.forName和ClassLoader区别

Java中Class.forName和classloader都可以用来对类进行加载。

  • Class.forName(“className”);

    其实这种方法调运的是:Class.forName(className, true, ClassLoader.getCallerClassLoader())方法
    参数一:className,需要加载的类的名称。
    参数二:true,是否对class进行初始化(需要initialize)
    参数三:classLoader,对应的类加载器
  • ClassLoader.laodClass(“className”);

    其实这种方法调运的是:ClassLoader.loadClass(name, false)方法
    参数一:name,需要加载的类的名称
    参数二:false,这个类加载以后是否需要去连接(不需要linking)

可见Class.forName除了将类的.class文件加载到jvm中之外,还会对类进行解释,执行类中的static块。

而classloader只干一件事情,就是将.class文件加载到jvm中,不会执行static中的内容,只有在newInstance才会去执行static块。

传送门

tomcat结构,类加载器流程

Tomcat 的总体结构

image.png

从上图中可以看出 Tomcat 的心脏是两个组件:Connector 和 Container,关于这两个组件将在后面详细介绍。Connector 组件是可以被替换,这样可以提供给服务器设计者更多的选择,因为这个组件是如此重要,不仅跟服务器的设计的本身,而且和不同的应用场景也十分相关,所以一个 Container 可以选择对应多个 Connector。多个 Connector 和一个 Container 就形成了一个 Service,Service 的概念大家都很熟悉了,有了 Service 就可以对外提供服务了,但是 Service 还要一个生存的环境,必须要有人能够给她生命、掌握其生死大权,那就非 Server 莫属了。所以整个 Tomcat 的生命周期由 Server 控制。

什么是类加载器?
虚拟机设计团队把类加载阶段中的“通过一个类的全限定名来获取描述此类的二进制字节流”这个动作放到Java虚拟机外部去实现,以便让应用程序自己决定如何去获取所需要的类。实现这个动作的代码模块称为“类加载器”。

传送门

讲讲Spring事务的传播属性,AOP原理,动态代理与cglib实现的区别,AOP有哪几种实现方式

Spring的beanFactory和factoryBean的区别

Spring加载流程

Spring如何管理事务的

多线程

线城池的最大线程数目根据什么确定

多线程的几种实现方式,什么是线程安全,什么是重排序

volatile的原理,作用,能代替锁么

sleep和wait的区别,以及wait的实现原理

Lock与synchronized 的区别,synchronized 的原理,什么是自旋锁,偏向锁,轻量级锁,什么叫可重入锁,什么叫公平锁和非公平锁

用过哪些原子类,他们的参数以及原理是什么

用过哪些线程池,他们的原理简单概括下,构造函数的各个参数的含义,比如coreSize,maxsize等

有一个第三方接口,有很多个线程去调用获取数据,现在规定每秒钟最多有10个线程同时调用它,如何做到。

spring的controller是单例还是多例,怎么保证并发的安全

用三个线程按顺序循环打印abc三个字母,比如abcabcabc

ThreadLocal用过么,原理是什么,用的时候要注意什么

如果让你实现一个并发安全的链表,你会怎么做

JVM相关

jvm中一次完整的GC流程(从ygc到fgc)是怎样的,重点讲讲对象如何晋升到老年代,几种主要的jvm参数等

你知道哪几种垃圾收集器,各自的优缺点,重点讲下cms

当出现了内存溢出,你怎么排错

JVM内存模型的相关知识了解多少

简单说说你了解的类加载器

JAVA的反射机制

网络

http1.0和http1.1有什么区别

TCP三次握手和四次挥手的流程,为什么断开连接要4次,如果握手只有两次,会出现什么

TIME_WAIT和CLOSE_WAIT的区别

说说你知道的几种HTTP响应码

当你用浏览器打开一个链接的时候,计算机做了哪些工作步骤

Linux下IO模型有几种,各自的含义是什么

TCP/IP如何保证可靠性,数据包有哪些数据组成

架构设计与分布式:

tomcat如何调优,各种参数的意义

常见的缓存策略有哪些,你们项目中用到了什么缓存系统,如何设计的,Redis的使用要注意什么,持久化方式,内存设置,集群,淘汰策略等

如何防止缓存雪崩12.用java自己实现一个LRU

分布式集群下如何做到唯一序列号

设计一个秒杀系统,30分钟没付款就自动关闭交易

如何做一个分布式锁

用过哪些MQ,怎么用的,和其他mq比较有什么优缺点,MQ的连接是线程安全的吗

MQ系统的数据如何保证不丢失

分布式事务的原理,如何使用分布式事务

什么是一致性hash

什么是restful,讲讲你理解的restful

如何设计建立和保持100w的长连接?

解释什么是MESI协议(缓存一致性)

说说你知道的几种HASH算法,简单的也可以

什么是paxos算法

redis和memcached 的内存管理的区别

一个在线文档系统,文档可以被编辑,如何防止多人同时对同一份文档进行编辑更新

算法

10亿个数字里里面找最小的10个

有1亿个数字,其中有2个是重复的,快速找到它,时间和空间要最优

2亿个随机生成的无序整数,找出中间大小的值

遍历二叉树

数据库

数据库隔离级别有哪些,各自的含义是什么,MYsql默认的隔离级别是是什么,各个存储引擎优缺点

高并发下,如何做到安全的修改同一行数据,乐观锁和悲观锁是什么,INNODB的行级锁有哪2种,解释其含义

SQL优化的一般步骤是什么,怎么看执行计划,如何理解其中各个字段的含义,索引的原理?

数据库会死锁吗,举一个死锁的例子,mysql怎么解决死锁

MYsql的索引实现方式

聚集索引和非聚集索引的区别

数据库中 BTREE和B+tree区别

System类

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

import java.io.*;
import java.lang.reflect.Executable;
import java.lang.annotation.Annotation;
import java.security.AccessControlContext;
import java.util.Properties;
import java.util.PropertyPermission;
import java.util.StringTokenizer;
import java.util.Map;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.AllPermission;
import java.nio.channels.Channel;
import java.nio.channels.spi.SelectorProvider;
import sun.nio.ch.Interruptible;
import sun.reflect.CallerSensitive;
import sun.reflect.Reflection;
import sun.security.util.SecurityConstants;
import sun.reflect.annotation.AnnotationType;

/**
* The <code>System</code> class contains several useful class fields
* and methods. It cannot be instantiated.
*
* <p>Among the facilities provided by the <code>System</code> class
* are standard input, standard output, and error output streams;
* access to externally defined properties and environment
* variables; a means of loading files and libraries; and a utility
* method for quickly copying a portion of an array.
*
* @author unascribed
* @since JDK1.0
*/
public final class System {

/* register the natives via the static initializer.
*
* VM will invoke the initializeSystemClass method to complete
* the initialization for this class separated from clinit.
* Note that to use properties set by the VM, see the constraints
* described in the initializeSystemClass method.
*/
private static native void registerNatives();
static {
registerNatives();
}

/** Don't let anyone instantiate this class */
private System() {
}

/**
* The "standard" input stream. This stream is already
* open and ready to supply input data. Typically this stream
* corresponds to keyboard input or another input source specified by
* the host environment or user.
*/
public final static InputStream in = null;

/**
* The "standard" output stream. This stream is already
* open and ready to accept output data. Typically this stream
* corresponds to display output or another output destination
* specified by the host environment or user.
* <p>
* For simple stand-alone Java applications, a typical way to write
* a line of output data is:
* <blockquote><pre>
* System.out.println(data)
* </pre></blockquote>
* <p>
* See the <code>println</code> methods in class <code>PrintStream</code>.
*
* @see java.io.PrintStream#println()
* @see java.io.PrintStream#println(boolean)
* @see java.io.PrintStream#println(char)
* @see java.io.PrintStream#println(char[])
* @see java.io.PrintStream#println(double)
* @see java.io.PrintStream#println(float)
* @see java.io.PrintStream#println(int)
* @see java.io.PrintStream#println(long)
* @see java.io.PrintStream#println(java.lang.Object)
* @see java.io.PrintStream#println(java.lang.String)
*/
public final static PrintStream out = null;

/**
* The "standard" error output stream. This stream is already
* open and ready to accept output data.
* <p>
* Typically this stream corresponds to display output or another
* output destination specified by the host environment or user. By
* convention, this output stream is used to display error messages
* or other information that should come to the immediate attention
* of a user even if the principal output stream, the value of the
* variable <code>out</code>, has been redirected to a file or other
* destination that is typically not continuously monitored.
*/
public final static PrintStream err = null;

/* The security manager for the system.
*/
private static volatile SecurityManager security = null;

/**
* Reassigns the "standard" input stream.
*
* <p>First, if there is a security manager, its <code>checkPermission</code>
* method is called with a <code>RuntimePermission("setIO")</code> permission
* to see if it's ok to reassign the "standard" input stream.
* <p>
*
* @param in the new standard input stream.
*
* @throws SecurityException
* if a security manager exists and its
* <code>checkPermission</code> method doesn't allow
* reassigning of the standard input stream.
*
* @see SecurityManager#checkPermission
* @see java.lang.RuntimePermission
*
* @since JDK1.1
*/
public static void setIn(InputStream in) {
checkIO();
setIn0(in);
}

/**
* Reassigns the "standard" output stream.
*
* <p>First, if there is a security manager, its <code>checkPermission</code>
* method is called with a <code>RuntimePermission("setIO")</code> permission
* to see if it's ok to reassign the "standard" output stream.
*
* @param out the new standard output stream
*
* @throws SecurityException
* if a security manager exists and its
* <code>checkPermission</code> method doesn't allow
* reassigning of the standard output stream.
*
* @see SecurityManager#checkPermission
* @see java.lang.RuntimePermission
*
* @since JDK1.1
*/
public static void setOut(PrintStream out) {
checkIO();
setOut0(out);
}

/**
* Reassigns the "standard" error output stream.
*
* <p>First, if there is a security manager, its <code>checkPermission</code>
* method is called with a <code>RuntimePermission("setIO")</code> permission
* to see if it's ok to reassign the "standard" error output stream.
*
* @param err the new standard error output stream.
*
* @throws SecurityException
* if a security manager exists and its
* <code>checkPermission</code> method doesn't allow
* reassigning of the standard error output stream.
*
* @see SecurityManager#checkPermission
* @see java.lang.RuntimePermission
*
* @since JDK1.1
*/
public static void setErr(PrintStream err) {
checkIO();
setErr0(err);
}

private static volatile Console cons = null;
/**
* Returns the unique {@link java.io.Console Console} object associated
* with the current Java virtual machine, if any.
*
* @return The system console, if any, otherwise <tt>null</tt>.
*
* @since 1.6
*/
public static Console console() {
if (cons == null) {
synchronized (System.class) {
cons = sun.misc.SharedSecrets.getJavaIOAccess().console();
}
}
return cons;
}

/**
* Returns the channel inherited from the entity that created this
* Java virtual machine.
*
* <p> This method returns the channel obtained by invoking the
* {@link java.nio.channels.spi.SelectorProvider#inheritedChannel
* inheritedChannel} method of the system-wide default
* {@link java.nio.channels.spi.SelectorProvider} object. </p>
*
* <p> In addition to the network-oriented channels described in
* {@link java.nio.channels.spi.SelectorProvider#inheritedChannel
* inheritedChannel}, this method may return other kinds of
* channels in the future.
*
* @return The inherited channel, if any, otherwise <tt>null</tt>.
*
* @throws IOException
* If an I/O error occurs
*
* @throws SecurityException
* If a security manager is present and it does not
* permit access to the channel.
*
* @since 1.5
*/
public static Channel inheritedChannel() throws IOException {
return SelectorProvider.provider().inheritedChannel();
}

private static void checkIO() {
SecurityManager sm = getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission("setIO"));
}
}

private static native void setIn0(InputStream in);
private static native void setOut0(PrintStream out);
private static native void setErr0(PrintStream err);

/**
* Sets the System security.
*
* <p> If there is a security manager already installed, this method first
* calls the security manager's <code>checkPermission</code> method
* with a <code>RuntimePermission("setSecurityManager")</code>
* permission to ensure it's ok to replace the existing
* security manager.
* This may result in throwing a <code>SecurityException</code>.
*
* <p> Otherwise, the argument is established as the current
* security manager. If the argument is <code>null</code> and no
* security manager has been established, then no action is taken and
* the method simply returns.
*
* @param s the security manager.
* @exception SecurityException if the security manager has already
* been set and its <code>checkPermission</code> method
* doesn't allow it to be replaced.
* @see #getSecurityManager
* @see SecurityManager#checkPermission
* @see java.lang.RuntimePermission
*/
public static
void setSecurityManager(final SecurityManager s) {
try {
s.checkPackageAccess("java.lang");
} catch (Exception e) {
// no-op
}
setSecurityManager0(s);
}

private static synchronized
void setSecurityManager0(final SecurityManager s) {
SecurityManager sm = getSecurityManager();
if (sm != null) {
// ask the currently installed security manager if we
// can replace it.
sm.checkPermission(new RuntimePermission
("setSecurityManager"));
}

if ((s != null) && (s.getClass().getClassLoader() != null)) {
// New security manager class is not on bootstrap classpath.
// Cause policy to get initialized before we install the new
// security manager, in order to prevent infinite loops when
// trying to initialize the policy (which usually involves
// accessing some security and/or system properties, which in turn
// calls the installed security manager's checkPermission method
// which will loop infinitely if there is a non-system class
// (in this case: the new security manager class) on the stack).
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
s.getClass().getProtectionDomain().implies
(SecurityConstants.ALL_PERMISSION);
return null;
}
});
}

security = s;
}

/**
* Gets the system security interface.
*
* @return if a security manager has already been established for the
* current application, then that security manager is returned;
* otherwise, <code>null</code> is returned.
* @see #setSecurityManager
*/
public static SecurityManager getSecurityManager() {
return security;
}

/**
* Returns the current time in milliseconds. Note that
* while the unit of time of the return value is a millisecond,
* the granularity of the value depends on the underlying
* operating system and may be larger. For example, many
* operating systems measure time in units of tens of
* milliseconds.
*
* <p> See the description of the class <code>Date</code> for
* a discussion of slight discrepancies that may arise between
* "computer time" and coordinated universal time (UTC).
*
* @return the difference, measured in milliseconds, between
* the current time and midnight, January 1, 1970 UTC.
* @see java.util.Date
*/
public static native long currentTimeMillis();

/**
* Returns the current value of the running Java Virtual Machine's
* high-resolution time source, in nanoseconds.
*
* <p>This method can only be used to measure elapsed time and is
* not related to any other notion of system or wall-clock time.
* The value returned represents nanoseconds since some fixed but
* arbitrary <i>origin</i> time (perhaps in the future, so values
* may be negative). The same origin is used by all invocations of
* this method in an instance of a Java virtual machine; other
* virtual machine instances are likely to use a different origin.
*
* <p>This method provides nanosecond precision, but not necessarily
* nanosecond resolution (that is, how frequently the value changes)
* - no guarantees are made except that the resolution is at least as
* good as that of {@link #currentTimeMillis()}.
*
* <p>Differences in successive calls that span greater than
* approximately 292 years (2<sup>63</sup> nanoseconds) will not
* correctly compute elapsed time due to numerical overflow.
*
* <p>The values returned by this method become meaningful only when
* the difference between two such values, obtained within the same
* instance of a Java virtual machine, is computed.
*
* <p> For example, to measure how long some code takes to execute:
* <pre> {@code
* long startTime = System.nanoTime();
* // ... the code being measured ...
* long estimatedTime = System.nanoTime() - startTime;}</pre>
*
* <p>To compare two nanoTime values
* <pre> {@code
* long t0 = System.nanoTime();
* ...
* long t1 = System.nanoTime();}</pre>
*
* one should use {@code t1 - t0 < 0}, not {@code t1 < t0},
* because of the possibility of numerical overflow.
*
* @return the current value of the running Java Virtual Machine's
* high-resolution time source, in nanoseconds
* @since 1.5
*/
public static native long nanoTime();

/**
* Copies an array from the specified source array, beginning at the
* specified position, to the specified position of the destination array.
* A subsequence of array components are copied from the source
* array referenced by <code>src</code> to the destination array
* referenced by <code>dest</code>. The number of components copied is
* equal to the <code>length</code> argument. The components at
* positions <code>srcPos</code> through
* <code>srcPos+length-1</code> in the source array are copied into
* positions <code>destPos</code> through
* <code>destPos+length-1</code>, respectively, of the destination
* array.
* <p>
* If the <code>src</code> and <code>dest</code> arguments refer to the
* same array object, then the copying is performed as if the
* components at positions <code>srcPos</code> through
* <code>srcPos+length-1</code> were first copied to a temporary
* array with <code>length</code> components and then the contents of
* the temporary array were copied into positions
* <code>destPos</code> through <code>destPos+length-1</code> of the
* destination array.
* <p>
* If <code>dest</code> is <code>null</code>, then a
* <code>NullPointerException</code> is thrown.
* <p>
* If <code>src</code> is <code>null</code>, then a
* <code>NullPointerException</code> is thrown and the destination
* array is not modified.
* <p>
* Otherwise, if any of the following is true, an
* <code>ArrayStoreException</code> is thrown and the destination is
* not modified:
* <ul>
* <li>The <code>src</code> argument refers to an object that is not an
* array.
* <li>The <code>dest</code> argument refers to an object that is not an
* array.
* <li>The <code>src</code> argument and <code>dest</code> argument refer
* to arrays whose component types are different primitive types.
* <li>The <code>src</code> argument refers to an array with a primitive
* component type and the <code>dest</code> argument refers to an array
* with a reference component type.
* <li>The <code>src</code> argument refers to an array with a reference
* component type and the <code>dest</code> argument refers to an array
* with a primitive component type.
* </ul>
* <p>
* Otherwise, if any of the following is true, an
* <code>IndexOutOfBoundsException</code> is
* thrown and the destination is not modified:
* <ul>
* <li>The <code>srcPos</code> argument is negative.
* <li>The <code>destPos</code> argument is negative.
* <li>The <code>length</code> argument is negative.
* <li><code>srcPos+length</code> is greater than
* <code>src.length</code>, the length of the source array.
* <li><code>destPos+length</code> is greater than
* <code>dest.length</code>, the length of the destination array.
* </ul>
* <p>
* Otherwise, if any actual component of the source array from
* position <code>srcPos</code> through
* <code>srcPos+length-1</code> cannot be converted to the component
* type of the destination array by assignment conversion, an
* <code>ArrayStoreException</code> is thrown. In this case, let
* <b><i>k</i></b> be the smallest nonnegative integer less than
* length such that <code>src[srcPos+</code><i>k</i><code>]</code>
* cannot be converted to the component type of the destination
* array; when the exception is thrown, source array components from
* positions <code>srcPos</code> through
* <code>srcPos+</code><i>k</i><code>-1</code>
* will already have been copied to destination array positions
* <code>destPos</code> through
* <code>destPos+</code><i>k</I><code>-1</code> and no other
* positions of the destination array will have been modified.
* (Because of the restrictions already itemized, this
* paragraph effectively applies only to the situation where both
* arrays have component types that are reference types.)
*
* @param src the source array.
* @param srcPos starting position in the source array.
* @param dest the destination array.
* @param destPos starting position in the destination data.
* @param length the number of array elements to be copied.
* @exception IndexOutOfBoundsException if copying would cause
* access of data outside array bounds.
* @exception ArrayStoreException if an element in the <code>src</code>
* array could not be stored into the <code>dest</code> array
* because of a type mismatch.
* @exception NullPointerException if either <code>src</code> or
* <code>dest</code> is <code>null</code>.
*/
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);

/**
* Returns the same hash code for the given object as
* would be returned by the default method hashCode(),
* whether or not the given object's class overrides
* hashCode().
* The hash code for the null reference is zero.
*
* @param x object for which the hashCode is to be calculated
* @return the hashCode
* @since JDK1.1
*/
public static native int identityHashCode(Object x);

/**
* System properties. The following properties are guaranteed to be defined:
* <dl>
* <dt>java.version <dd>Java version number
* <dt>java.vendor <dd>Java vendor specific string
* <dt>java.vendor.url <dd>Java vendor URL
* <dt>java.home <dd>Java installation directory
* <dt>java.class.version <dd>Java class version number
* <dt>java.class.path <dd>Java classpath
* <dt>os.name <dd>Operating System Name
* <dt>os.arch <dd>Operating System Architecture
* <dt>os.version <dd>Operating System Version
* <dt>file.separator <dd>File separator ("/" on Unix)
* <dt>path.separator <dd>Path separator (":" on Unix)
* <dt>line.separator <dd>Line separator ("\n" on Unix)
* <dt>user.name <dd>User account name
* <dt>user.home <dd>User home directory
* <dt>user.dir <dd>User's current working directory
* </dl>
*/

private static Properties props;
private static native Properties initProperties(Properties props);

/**
* Determines the current system properties.
* <p>
* First, if there is a security manager, its
* <code>checkPropertiesAccess</code> method is called with no
* arguments. This may result in a security exception.
* <p>
* The current set of system properties for use by the
* {@link #getProperty(String)} method is returned as a
* <code>Properties</code> object. If there is no current set of
* system properties, a set of system properties is first created and
* initialized. This set of system properties always includes values
* for the following keys:
* <table summary="Shows property keys and associated values">
* <tr><th>Key</th>
* <th>Description of Associated Value</th></tr>
* <tr><td><code>java.version</code></td>
* <td>Java Runtime Environment version</td></tr>
* <tr><td><code>java.vendor</code></td>
* <td>Java Runtime Environment vendor</td></tr>
* <tr><td><code>java.vendor.url</code></td>
* <td>Java vendor URL</td></tr>
* <tr><td><code>java.home</code></td>
* <td>Java installation directory</td></tr>
* <tr><td><code>java.vm.specification.version</code></td>
* <td>Java Virtual Machine specification version</td></tr>
* <tr><td><code>java.vm.specification.vendor</code></td>
* <td>Java Virtual Machine specification vendor</td></tr>
* <tr><td><code>java.vm.specification.name</code></td>
* <td>Java Virtual Machine specification name</td></tr>
* <tr><td><code>java.vm.version</code></td>
* <td>Java Virtual Machine implementation version</td></tr>
* <tr><td><code>java.vm.vendor</code></td>
* <td>Java Virtual Machine implementation vendor</td></tr>
* <tr><td><code>java.vm.name</code></td>
* <td>Java Virtual Machine implementation name</td></tr>
* <tr><td><code>java.specification.version</code></td>
* <td>Java Runtime Environment specification version</td></tr>
* <tr><td><code>java.specification.vendor</code></td>
* <td>Java Runtime Environment specification vendor</td></tr>
* <tr><td><code>java.specification.name</code></td>
* <td>Java Runtime Environment specification name</td></tr>
* <tr><td><code>java.class.version</code></td>
* <td>Java class format version number</td></tr>
* <tr><td><code>java.class.path</code></td>
* <td>Java class path</td></tr>
* <tr><td><code>java.library.path</code></td>
* <td>List of paths to search when loading libraries</td></tr>
* <tr><td><code>java.io.tmpdir</code></td>
* <td>Default temp file path</td></tr>
* <tr><td><code>java.compiler</code></td>
* <td>Name of JIT compiler to use</td></tr>
* <tr><td><code>java.ext.dirs</code></td>
* <td>Path of extension directory or directories
* <b>Deprecated.</b> <i>This property, and the mechanism
* which implements it, may be removed in a future
* release.</i> </td></tr>
* <tr><td><code>os.name</code></td>
* <td>Operating system name</td></tr>
* <tr><td><code>os.arch</code></td>
* <td>Operating system architecture</td></tr>
* <tr><td><code>os.version</code></td>
* <td>Operating system version</td></tr>
* <tr><td><code>file.separator</code></td>
* <td>File separator ("/" on UNIX)</td></tr>
* <tr><td><code>path.separator</code></td>
* <td>Path separator (":" on UNIX)</td></tr>
* <tr><td><code>line.separator</code></td>
* <td>Line separator ("\n" on UNIX)</td></tr>
* <tr><td><code>user.name</code></td>
* <td>User's account name</td></tr>
* <tr><td><code>user.home</code></td>
* <td>User's home directory</td></tr>
* <tr><td><code>user.dir</code></td>
* <td>User's current working directory</td></tr>
* </table>
* <p>
* Multiple paths in a system property value are separated by the path
* separator character of the platform.
* <p>
* Note that even if the security manager does not permit the
* <code>getProperties</code> operation, it may choose to permit the
* {@link #getProperty(String)} operation.
*
* @return the system properties
* @exception SecurityException if a security manager exists and its
* <code>checkPropertiesAccess</code> method doesn't allow access
* to the system properties.
* @see #setProperties
* @see java.lang.SecurityException
* @see java.lang.SecurityManager#checkPropertiesAccess()
* @see java.util.Properties
*/
public static Properties getProperties() {
SecurityManager sm = getSecurityManager();
if (sm != null) {
sm.checkPropertiesAccess();
}

return props;
}

/**
* Returns the system-dependent line separator string. It always
* returns the same value - the initial value of the {@linkplain
* #getProperty(String) system property} {@code line.separator}.
*
* <p>On UNIX systems, it returns {@code "\n"}; on Microsoft
* Windows systems it returns {@code "\r\n"}.
*
* @return the system-dependent line separator string
* @since 1.7
*/
public static String lineSeparator() {
return lineSeparator;
}

private static String lineSeparator;

/**
* Sets the system properties to the <code>Properties</code>
* argument.
* <p>
* First, if there is a security manager, its
* <code>checkPropertiesAccess</code> method is called with no
* arguments. This may result in a security exception.
* <p>
* The argument becomes the current set of system properties for use
* by the {@link #getProperty(String)} method. If the argument is
* <code>null</code>, then the current set of system properties is
* forgotten.
*
* @param props the new system properties.
* @exception SecurityException if a security manager exists and its
* <code>checkPropertiesAccess</code> method doesn't allow access
* to the system properties.
* @see #getProperties
* @see java.util.Properties
* @see java.lang.SecurityException
* @see java.lang.SecurityManager#checkPropertiesAccess()
*/
public static void setProperties(Properties props) {
SecurityManager sm = getSecurityManager();
if (sm != null) {
sm.checkPropertiesAccess();
}
if (props == null) {
props = new Properties();
initProperties(props);
}
System.props = props;
}

/**
* Gets the system property indicated by the specified key.
* <p>
* First, if there is a security manager, its
* <code>checkPropertyAccess</code> method is called with the key as
* its argument. This may result in a SecurityException.
* <p>
* If there is no current set of system properties, a set of system
* properties is first created and initialized in the same manner as
* for the <code>getProperties</code> method.
*
* @param key the name of the system property.
* @return the string value of the system property,
* or <code>null</code> if there is no property with that key.
*
* @exception SecurityException if a security manager exists and its
* <code>checkPropertyAccess</code> method doesn't allow
* access to the specified system property.
* @exception NullPointerException if <code>key</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>key</code> is empty.
* @see #setProperty
* @see java.lang.SecurityException
* @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
* @see java.lang.System#getProperties()
*/
public static String getProperty(String key) {
checkKey(key);
SecurityManager sm = getSecurityManager();
if (sm != null) {
sm.checkPropertyAccess(key);
}

return props.getProperty(key);
}

/**
* Gets the system property indicated by the specified key.
* <p>
* First, if there is a security manager, its
* <code>checkPropertyAccess</code> method is called with the
* <code>key</code> as its argument.
* <p>
* If there is no current set of system properties, a set of system
* properties is first created and initialized in the same manner as
* for the <code>getProperties</code> method.
*
* @param key the name of the system property.
* @param def a default value.
* @return the string value of the system property,
* or the default value if there is no property with that key.
*
* @exception SecurityException if a security manager exists and its
* <code>checkPropertyAccess</code> method doesn't allow
* access to the specified system property.
* @exception NullPointerException if <code>key</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>key</code> is empty.
* @see #setProperty
* @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
* @see java.lang.System#getProperties()
*/
public static String getProperty(String key, String def) {
checkKey(key);
SecurityManager sm = getSecurityManager();
if (sm != null) {
sm.checkPropertyAccess(key);
}

return props.getProperty(key, def);
}

/**
* Sets the system property indicated by the specified key.
* <p>
* First, if a security manager exists, its
* <code>SecurityManager.checkPermission</code> method
* is called with a <code>PropertyPermission(key, "write")</code>
* permission. This may result in a SecurityException being thrown.
* If no exception is thrown, the specified property is set to the given
* value.
* <p>
*
* @param key the name of the system property.
* @param value the value of the system property.
* @return the previous value of the system property,
* or <code>null</code> if it did not have one.
*
* @exception SecurityException if a security manager exists and its
* <code>checkPermission</code> method doesn't allow
* setting of the specified property.
* @exception NullPointerException if <code>key</code> or
* <code>value</code> is <code>null</code>.
* @exception IllegalArgumentException if <code>key</code> is empty.
* @see #getProperty
* @see java.lang.System#getProperty(java.lang.String)
* @see java.lang.System#getProperty(java.lang.String, java.lang.String)
* @see java.util.PropertyPermission
* @see SecurityManager#checkPermission
* @since 1.2
*/
public static String setProperty(String key, String value) {
checkKey(key);
SecurityManager sm = getSecurityManager();
if (sm != null) {
sm.checkPermission(new PropertyPermission(key,
SecurityConstants.PROPERTY_WRITE_ACTION));
}

return (String) props.setProperty(key, value);
}

/**
* Removes the system property indicated by the specified key.
* <p>
* First, if a security manager exists, its
* <code>SecurityManager.checkPermission</code> method
* is called with a <code>PropertyPermission(key, "write")</code>
* permission. This may result in a SecurityException being thrown.
* If no exception is thrown, the specified property is removed.
* <p>
*
* @param key the name of the system property to be removed.
* @return the previous string value of the system property,
* or <code>null</code> if there was no property with that key.
*
* @exception SecurityException if a security manager exists and its
* <code>checkPropertyAccess</code> method doesn't allow
* access to the specified system property.
* @exception NullPointerException if <code>key</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>key</code> is empty.
* @see #getProperty
* @see #setProperty
* @see java.util.Properties
* @see java.lang.SecurityException
* @see java.lang.SecurityManager#checkPropertiesAccess()
* @since 1.5
*/
public static String clearProperty(String key) {
checkKey(key);
SecurityManager sm = getSecurityManager();
if (sm != null) {
sm.checkPermission(new PropertyPermission(key, "write"));
}

return (String) props.remove(key);
}

private static void checkKey(String key) {
if (key == null) {
throw new NullPointerException("key can't be null");
}
if (key.equals("")) {
throw new IllegalArgumentException("key can't be empty");
}
}

/**
* Gets the value of the specified environment variable. An
* environment variable is a system-dependent external named
* value.
*
* <p>If a security manager exists, its
* {@link SecurityManager#checkPermission checkPermission}
* method is called with a
* <code>{@link RuntimePermission}("getenv."+name)</code>
* permission. This may result in a {@link SecurityException}
* being thrown. If no exception is thrown the value of the
* variable <code>name</code> is returned.
*
* <p><a name="EnvironmentVSSystemProperties"><i>System
* properties</i> and <i>environment variables</i></a> are both
* conceptually mappings between names and values. Both
* mechanisms can be used to pass user-defined information to a
* Java process. Environment variables have a more global effect,
* because they are visible to all descendants of the process
* which defines them, not just the immediate Java subprocess.
* They can have subtly different semantics, such as case
* insensitivity, on different operating systems. For these
* reasons, environment variables are more likely to have
* unintended side effects. It is best to use system properties
* where possible. Environment variables should be used when a
* global effect is desired, or when an external system interface
* requires an environment variable (such as <code>PATH</code>).
*
* <p>On UNIX systems the alphabetic case of <code>name</code> is
* typically significant, while on Microsoft Windows systems it is
* typically not. For example, the expression
* <code>System.getenv("FOO").equals(System.getenv("foo"))</code>
* is likely to be true on Microsoft Windows.
*
* @param name the name of the environment variable
* @return the string value of the variable, or <code>null</code>
* if the variable is not defined in the system environment
* @throws NullPointerException if <code>name</code> is <code>null</code>
* @throws SecurityException
* if a security manager exists and its
* {@link SecurityManager#checkPermission checkPermission}
* method doesn't allow access to the environment variable
* <code>name</code>
* @see #getenv()
* @see ProcessBuilder#environment()
*/
public static String getenv(String name) {
SecurityManager sm = getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission("getenv."+name));
}

return ProcessEnvironment.getenv(name);
}


/**
* Returns an unmodifiable string map view of the current system environment.
* The environment is a system-dependent mapping from names to
* values which is passed from parent to child processes.
*
* <p>If the system does not support environment variables, an
* empty map is returned.
*
* <p>The returned map will never contain null keys or values.
* Attempting to query the presence of a null key or value will
* throw a {@link NullPointerException}. Attempting to query
* the presence of a key or value which is not of type
* {@link String} will throw a {@link ClassCastException}.
*
* <p>The returned map and its collection views may not obey the
* general contract of the {@link Object#equals} and
* {@link Object#hashCode} methods.
*
* <p>The returned map is typically case-sensitive on all platforms.
*
* <p>If a security manager exists, its
* {@link SecurityManager#checkPermission checkPermission}
* method is called with a
* <code>{@link RuntimePermission}("getenv.*")</code>
* permission. This may result in a {@link SecurityException} being
* thrown.
*
* <p>When passing information to a Java subprocess,
* <a href=#EnvironmentVSSystemProperties>system properties</a>
* are generally preferred over environment variables.
*
* @return the environment as a map of variable names to values
* @throws SecurityException
* if a security manager exists and its
* {@link SecurityManager#checkPermission checkPermission}
* method doesn't allow access to the process environment
* @see #getenv(String)
* @see ProcessBuilder#environment()
* @since 1.5
*/
public static java.util.Map<String,String> getenv() {
SecurityManager sm = getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission("getenv.*"));
}

return ProcessEnvironment.getenv();
}

/**
* Terminates the currently running Java Virtual Machine. The
* argument serves as a status code; by convention, a nonzero status
* code indicates abnormal termination.
* <p>
* This method calls the <code>exit</code> method in class
* <code>Runtime</code>. This method never returns normally.
* <p>
* The call <code>System.exit(n)</code> is effectively equivalent to
* the call:
* <blockquote><pre>
* Runtime.getRuntime().exit(n)
* </pre></blockquote>
*
* @param status exit status.
* @throws SecurityException
* if a security manager exists and its <code>checkExit</code>
* method doesn't allow exit with the specified status.
* @see java.lang.Runtime#exit(int)
*/
public static void exit(int status) {
Runtime.getRuntime().exit(status);
}

/**
* Runs the garbage collector.
* <p>
* Calling the <code>gc</code> method suggests that the Java Virtual
* Machine expend effort toward recycling unused objects in order to
* make the memory they currently occupy available for quick reuse.
* When control returns from the method call, the Java Virtual
* Machine has made a best effort to reclaim space from all discarded
* objects.
* <p>
* The call <code>System.gc()</code> is effectively equivalent to the
* call:
* <blockquote><pre>
* Runtime.getRuntime().gc()
* </pre></blockquote>
*
* @see java.lang.Runtime#gc()
*/
public static void gc() {
Runtime.getRuntime().gc();
}

/**
* Runs the finalization methods of any objects pending finalization.
* <p>
* Calling this method suggests that the Java Virtual Machine expend
* effort toward running the <code>finalize</code> methods of objects
* that have been found to be discarded but whose <code>finalize</code>
* methods have not yet been run. When control returns from the
* method call, the Java Virtual Machine has made a best effort to
* complete all outstanding finalizations.
* <p>
* The call <code>System.runFinalization()</code> is effectively
* equivalent to the call:
* <blockquote><pre>
* Runtime.getRuntime().runFinalization()
* </pre></blockquote>
*
* @see java.lang.Runtime#runFinalization()
*/
public static void runFinalization() {
Runtime.getRuntime().runFinalization();
}

/**
* Enable or disable finalization on exit; doing so specifies that the
* finalizers of all objects that have finalizers that have not yet been
* automatically invoked are to be run before the Java runtime exits.
* By default, finalization on exit is disabled.
*
* <p>If there is a security manager,
* its <code>checkExit</code> method is first called
* with 0 as its argument to ensure the exit is allowed.
* This could result in a SecurityException.
*
* @deprecated This method is inherently unsafe. It may result in
* finalizers being called on live objects while other threads are
* concurrently manipulating those objects, resulting in erratic
* behavior or deadlock.
* @param value indicating enabling or disabling of finalization
* @throws SecurityException
* if a security manager exists and its <code>checkExit</code>
* method doesn't allow the exit.
*
* @see java.lang.Runtime#exit(int)
* @see java.lang.Runtime#gc()
* @see java.lang.SecurityManager#checkExit(int)
* @since JDK1.1
*/
@Deprecated
public static void runFinalizersOnExit(boolean value) {
Runtime.runFinalizersOnExit(value);
}

/**
* Loads the native library specified by the filename argument. The filename
* argument must be an absolute path name.
*
* If the filename argument, when stripped of any platform-specific library
* prefix, path, and file extension, indicates a library whose name is,
* for example, L, and a native library called L is statically linked
* with the VM, then the JNI_OnLoad_L function exported by the library
* is invoked rather than attempting to load a dynamic library.
* A filename matching the argument does not have to exist in the
* file system.
* See the JNI Specification for more details.
*
* Otherwise, the filename argument is mapped to a native library image in
* an implementation-dependent manner.
*
* <p>
* The call <code>System.load(name)</code> is effectively equivalent
* to the call:
* <blockquote><pre>
* Runtime.getRuntime().load(name)
* </pre></blockquote>
*
* @param filename the file to load.
* @exception SecurityException if a security manager exists and its
* <code>checkLink</code> method doesn't allow
* loading of the specified dynamic library
* @exception UnsatisfiedLinkError if either the filename is not an
* absolute path name, the native library is not statically
* linked with the VM, or the library cannot be mapped to
* a native library image by the host system.
* @exception NullPointerException if <code>filename</code> is
* <code>null</code>
* @see java.lang.Runtime#load(java.lang.String)
* @see java.lang.SecurityManager#checkLink(java.lang.String)
*/
@CallerSensitive
public static void load(String filename) {
Runtime.getRuntime().load0(Reflection.getCallerClass(), filename);
}

/**
* Loads the native library specified by the <code>libname</code>
* argument. The <code>libname</code> argument must not contain any platform
* specific prefix, file extension or path. If a native library
* called <code>libname</code> is statically linked with the VM, then the
* JNI_OnLoad_<code>libname</code> function exported by the library is invoked.
* See the JNI Specification for more details.
*
* Otherwise, the libname argument is loaded from a system library
* location and mapped to a native library image in an implementation-
* dependent manner.
* <p>
* The call <code>System.loadLibrary(name)</code> is effectively
* equivalent to the call
* <blockquote><pre>
* Runtime.getRuntime().loadLibrary(name)
* </pre></blockquote>
*
* @param libname the name of the library.
* @exception SecurityException if a security manager exists and its
* <code>checkLink</code> method doesn't allow
* loading of the specified dynamic library
* @exception UnsatisfiedLinkError if either the libname argument
* contains a file path, the native library is not statically
* linked with the VM, or the library cannot be mapped to a
* native library image by the host system.
* @exception NullPointerException if <code>libname</code> is
* <code>null</code>
* @see java.lang.Runtime#loadLibrary(java.lang.String)
* @see java.lang.SecurityManager#checkLink(java.lang.String)
*/
@CallerSensitive
public static void loadLibrary(String libname) {
Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname);
}

/**
* Maps a library name into a platform-specific string representing
* a native library.
*
* @param libname the name of the library.
* @return a platform-dependent native library name.
* @exception NullPointerException if <code>libname</code> is
* <code>null</code>
* @see java.lang.System#loadLibrary(java.lang.String)
* @see java.lang.ClassLoader#findLibrary(java.lang.String)
* @since 1.2
*/
public static native String mapLibraryName(String libname);

/**
* Create PrintStream for stdout/err based on encoding.
*/
private static PrintStream newPrintStream(FileOutputStream fos, String enc) {
if (enc != null) {
try {
return new PrintStream(new BufferedOutputStream(fos, 128), true, enc);
} catch (UnsupportedEncodingException uee) {}
}
return new PrintStream(new BufferedOutputStream(fos, 128), true);
}


/**
* Initialize the system class. Called after thread initialization.
*/
private static void initializeSystemClass() {

// VM might invoke JNU_NewStringPlatform() to set those encoding
// sensitive properties (user.home, user.name, boot.class.path, etc.)
// during "props" initialization, in which it may need access, via
// System.getProperty(), to the related system encoding property that
// have been initialized (put into "props") at early stage of the
// initialization. So make sure the "props" is available at the
// very beginning of the initialization and all system properties to
// be put into it directly.
props = new Properties();
initProperties(props); // initialized by the VM

// There are certain system configurations that may be controlled by
// VM options such as the maximum amount of direct memory and
// Integer cache size used to support the object identity semantics
// of autoboxing. Typically, the library will obtain these values
// from the properties set by the VM. If the properties are for
// internal implementation use only, these properties should be
// removed from the system properties.
//
// See java.lang.Integer.IntegerCache and the
// sun.misc.VM.saveAndRemoveProperties method for example.
//
// Save a private copy of the system properties object that
// can only be accessed by the internal implementation. Remove
// certain system properties that are not intended for public access.
sun.misc.VM.saveAndRemoveProperties(props);


lineSeparator = props.getProperty("line.separator");
sun.misc.Version.init();

FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
setIn0(new BufferedInputStream(fdIn));
setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding")));
setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding")));

// Load the zip library now in order to keep java.util.zip.ZipFile
// from trying to use itself to load this library later.
loadLibrary("zip");

// Setup Java signal handlers for HUP, TERM, and INT (where available).
Terminator.setup();

// Initialize any miscellenous operating system settings that need to be
// set for the class libraries. Currently this is no-op everywhere except
// for Windows where the process-wide error mode is set before the java.io
// classes are used.
sun.misc.VM.initializeOSEnvironment();

// The main thread is not added to its thread group in the same
// way as other threads; we must do it ourselves here.
Thread current = Thread.currentThread();
current.getThreadGroup().add(current);

// register shared secrets
setJavaLangAccess();

// Subsystems that are invoked during initialization can invoke
// sun.misc.VM.isBooted() in order to avoid doing things that should
// wait until the application class loader has been set up.
// IMPORTANT: Ensure that this remains the last initialization action!
sun.misc.VM.booted();
}

private static void setJavaLangAccess() {
// Allow privileged classes outside of java.lang
sun.misc.SharedSecrets.setJavaLangAccess(new sun.misc.JavaLangAccess(){
public sun.reflect.ConstantPool getConstantPool(Class<?> klass) {
return klass.getConstantPool();
}
public boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType) {
return klass.casAnnotationType(oldType, newType);
}
public AnnotationType getAnnotationType(Class<?> klass) {
return klass.getAnnotationType();
}
public Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap(Class<?> klass) {
return klass.getDeclaredAnnotationMap();
}
public byte[] getRawClassAnnotations(Class<?> klass) {
return klass.getRawAnnotations();
}
public byte[] getRawClassTypeAnnotations(Class<?> klass) {
return klass.getRawTypeAnnotations();
}
public byte[] getRawExecutableTypeAnnotations(Executable executable) {
return Class.getExecutableTypeAnnotationBytes(executable);
}
public <E extends Enum<E>>
E[] getEnumConstantsShared(Class<E> klass) {
return klass.getEnumConstantsShared();
}
public void blockedOn(Thread t, Interruptible b) {
t.blockedOn(b);
}
public void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook) {
Shutdown.add(slot, registerShutdownInProgress, hook);
}
public int getStackTraceDepth(Throwable t) {
return t.getStackTraceDepth();
}
public StackTraceElement getStackTraceElement(Throwable t, int i) {
return t.getStackTraceElement(i);
}
public String newStringUnsafe(char[] chars) {
return new String(chars, true);
}
public Thread newThreadWithAcc(Runnable target, AccessControlContext acc) {
return new Thread(target, acc);
}
public void invokeFinalize(Object o) throws Throwable {
o.finalize();
}
});
}
}

Java反编译工具jad

image.png

Jad(JAva Decompiler)

Jad(JAva Decompiler)是一个Java的反编译器,可以通过命令行把Java的class文件反编译成源代码。下载点击

使用方法:

[1] 反编译一个class文件:jad example.class,会生成example.jad,用文本编辑器打开就是java源代码

[2] 指定生成源代码的后缀名:jad -sjava example.class,生成example.java

[3] 改变生成的源代码的名称,可以先使用-p将反编译后的源代码输出到控制台窗口,然后使用重定向,输出到文件:jad -p example.class > myexample.java

[4] 把源代码文件输出到指定的目录:jad -dnewdir -sjava example.class,在newdir目录下生成example.java

[5] 把packages目录下的class文件全部反编译:jad -sjava packages/*.class

[6] 把packages目录以及子目录下的文件全部反编译:jad -sjava packages/*/.class,不过你仍然会发现所有的源代码文件被放到了同一个文件中,没有按照class文件的包路径建立起路径

[7] 把packages目录以及子目录下的文件全部反编译并建立和java包一致的文件夹路径,可以使用-r命令:jad -r -sjava packages/*/.class

[8] 当重复使用命令反编译时,Jad会提示“whether you want to overwrite it or not”,使用-o可以强制覆盖旧文件

[9] 还有其他的参数可以设置生成的源代码的格式,可以输入jad命令查看帮助,这里有个人做了简单的翻译:jad命令总结

[10] 当然,你会发现有些源文件头部有些注释信息,不用找了,jad没有参数可以去掉它,用别的办法吧。

测试

Main.java

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

public class Main {

static volatile int t = 0;
public static void main(String[] args) {
int n = 100;
Thread[] threads = new Thread[n];
for (int i = 0; i < n; i++) {
threads[i] = new Thread(new Runnable() {

@Override
public void run() {
for (int i = 0; i < 10000; i++) {
add();
}
}
});
threads[i].start();
}

while (Thread.activeCount() > 1)
Thread.yield();

System.out.println(t);
}

static void add() {
t++;
}
}

Main.class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
cafe babe 0000 0034 0037 0a00 0d00 1d07
001e 0700 1f0a 0003 001d 0a00 0200 200a
0002 0021 0a00 0200 220a 0002 0023 0900
2400 2509 000c 0026 0a00 2700 2807 0029
0700 2a01 000c 496e 6e65 7243 6c61 7373
6573 0100 0174 0100 0149 0100 063c 696e
6974 3e01 0003 2829 5601 0004 436f 6465
0100 0f4c 696e 654e 756d 6265 7254 6162
6c65 0100 046d 6169 6e01 0016 285b 4c6a
6176 612f 6c61 6e67 2f53 7472 696e 673b
2956 0100 0d53 7461 636b 4d61 7054 6162
6c65 0700 2b01 0003 6164 6401 0008 3c63
6c69 6e69 743e 0100 0a53 6f75 7263 6546
696c 6501 0009 4d61 696e 2e6a 6176 610c
0011 0012 0100 106a 6176 612f 6c61 6e67
2f54 6872 6561 6401 0006 4d61 696e 2431
...

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
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name: Main.java

import java.io.PrintStream;

public class Main
{

public Main()
{
}

public static void main(String args[])
{
byte byte0 = 100;
Thread athread[] = new Thread[byte0];
for(int i = 0; i < byte0; i++)
{
athread[i] = new Thread(new Runnable() {

public void run()
{
for(int j = 0; j < 10000; j++)
Main.add();

}

}
);
athread[i].start();
}

for(; Thread.activeCount() > 1; Thread.yield());
System.out.println(t);
}

static void add()
{
t++;
}

static volatile int t = 0;

}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×