-
Notifications
You must be signed in to change notification settings - Fork 1
/
String.java
3272 lines (3027 loc) · 152 KB
/
String.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
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
/*
* Copyright (c) 1994, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang;
import jdk.internal.HotSpotIntrinsicCandidate;
import jdk.internal.vm.annotation.Stable;
import java.io.ObjectStreamField;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Native;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Formatter;
import java.util.Locale;
import java.util.Objects;
import java.util.Spliterator;
import java.util.StringJoiner;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* The {@code String} class represents character strings. All string literals in Java programs, such as {@code "abc"}, are implemented as instances of this class.
* <p>
* Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
* <blockquote><pre>
* String str = "abc";
* </pre></blockquote><p>
* is equivalent to:
* <blockquote><pre>
* char data[] = {'a', 'b', 'c'};
* String str = new String(data);
* </pre></blockquote><p>
* Here are some more examples of how strings can be used:
* <blockquote><pre>
* System.out.println("abc");
* String cde = "cde";
* System.out.println("abc" + cde);
* String c = "abc".substring(2,3);
* String d = cde.substring(1, 2);
* </pre></blockquote>
* <p>
* The class {@code String} includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the {@link Character Character} class.
* <p>
* The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see <i>The Java™ Language Specification</i>.
*
* <p> Unless otherwise noted, passing a {@code null} argument to a constructor
* or method in this class will cause a {@link NullPointerException} to be thrown.
*
* <p>A {@code String} represents a string in the UTF-16 format
* in which <em>supplementary characters</em> are represented by <em>surrogate pairs</em> (see the section <a href="Character.html#unicode">Unicode Character Representations</a> in the {@code Character} class for more information). Index values refer to {@code char} code units, so a supplementary character uses two positions in a {@code String}.
* <p>The {@code String} class provides methods for dealing with
* Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., {@code char} values).
*
* <p>Unless otherwise noted, methods for comparing Strings do not take locale
* into account. The {@link java.text.Collator} class provides methods for finer-grain, locale-sensitive String comparison.
*
* @author Lee Boynton
* @author Arthur van Hoff
* @author Martin Buchholz
* @author Ulf Zibis
* @implNote The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to <i>The Java™ Language Specification</i>. For example, the {@code javac} compiler may implement the operator with {@code StringBuffer}, {@code StringBuilder}, or {@code java.lang.invoke.StringConcatFactory} depending on the JDK version. The implementation of string conversion is typically through the method {@code toString}, defined by {@code Object} and inherited by all classes in Java.
* @jls 15.18.1 String Concatenation Operator +
* @see Object#toString()
* @see StringBuffer
* @see StringBuilder
* @see Charset
* @since 1.0
*/
/*
* 从JDK9开始,String对象不再以char[]形式存储,而是以名为value的byte[]形式存储。
*
* value有一个名为coder的编码标记,该标记有两种取值:LATIN1和UTF-16(UTF-16使用大端法还是小端法取决于系统)。
*
* Java中存储String的byte数组的默认编码是LATIN1(即ISO-8859-1)和UTF16。
*
* String由一系列Unicode符号组成,根据这些符号的Unicode编码范围[0x0, 0x10FFFF],将其分为两类:
* 符号1. 在[0x0, 0xFF]范围内的符号(属于LATIN1/ISO_8859_1字符集范围)
* 符号2. 在其他范围内的Unicode符号
* 对于第一类符号,其二进制形式仅用一个byte即可容纳,对于第二类符号,其二进制形式需用两个或四个UTF-16形式的byte存储。
*
* 由此,JDK内部将String的存储方式也分为两类:
* 第一类:String只包含符号1。这种类型的String里,每个符号使用一个byte存储。coder==LATIN1
* 第二类:String包含第二类符号。这种类型的String里,每个符号使用两个或四个UTF-16形式的byte存储(即使遇到符号1也使用两个byte存储)。coder==UTF16
*
* 为了便于后续描述这两类字符串,此处将第一类字符串称为LATIN1-String,将第二类字符串称为UTF16-String。
*
* 另注:
* 鉴于windows中以小端法存储数据,所以存储String的字节数组value也以UTF16小端法显示。
* 在后续的动态操作中,会将String转换为其他的编码(例如UTF_8、ISO_8859_1、US_ASCII、GBK等)形式。
* 如果不另指定编码形式,则以JVM的当前默认的字符集为依据去转换String。
*
* ★ 关于大端小端:
* 1.char永远是UTF-16大端
* 2.String(内置的value)永远取决于系统,在windows上是UTF-16小端
* 3 String外面的byte[],大小端取决于当时转换中所用的编码格式
*/
public final class String implements Serializable, Comparable<String>, CharSequence {
/**
* use serialVersionUID from JDK 1.0.2 for interoperability
*/
private static final long serialVersionUID = -6849794470754667710L;
/**
* Class String is special cased within the Serialization Stream Protocol.
*
* A String instance is written into an ObjectOutputStream according to
* <a href="{@docRoot}/../specs/serialization/protocol.html#stream-elements">
* Object Serialization Specification, Section 6.2, "Stream Elements"</a>
*/
private static final ObjectStreamField[] serialPersistentFields = new ObjectStreamField[0];
/**
* A Comparator that orders {@code String} objects as by {@code compareToIgnoreCase}. This comparator is serializable.
* <p>
* Note that this Comparator does <em>not</em> take locale into account, and will result in an unsatisfactory ordering for certain locales.
* The {@link java.text.Collator} class provides locale-sensitive comparison.
*
* @see java.text.Collator
* @since 1.2
*/
public static final Comparator<String> CASE_INSENSITIVE_ORDER = new CaseInsensitiveComparator();
/**
* If String compaction is disabled, the bytes in {@code value} are always encoded in UTF16.
* For methods with several possible implementation paths, when String compaction is disabled, only one code path is taken.
*
* The instance field value is generally opaque to optimizing JIT compilers.
* Therefore, in performance-sensitive place, an explicit check of the static boolean {@code COMPACT_STRINGS} is done
* first before checking the {@code coder} field since the static boolean {@code COMPACT_STRINGS}
* would be constant folded away by an optimizing JIT compiler.
*
* The idioms for these cases are as follows.
*
* For code such as:
*
* if (coder == LATIN1) { ... }
*
* can be written more optimally as
*
* if (coder() == LATIN1) { ... }
*
* or:
*
* if (COMPACT_STRINGS && coder == LATIN1) { ... }
*
* An optimizing JIT compiler can fold the above conditional as:
*
* COMPACT_STRINGS == true => if (coder == LATIN1) { ... }
* COMPACT_STRINGS == false => if (false) { ... }
*
* @implNote The actual value for this field is injected by JVM.
* The static initialization block is used to set the value here to communicate that this static final field is not statically foldable,
* and to avoid any possible circular dependency during vm initialization.
*/
// 如果禁用字符串压缩,则其字符始终以UTF-16编码,默认设置为true
static final boolean COMPACT_STRINGS;
/*
* Latin1是ISO-8859-1的别名,有些环境下写作Latin-1。ISO-8859-1编码是单字节编码,向下兼容ASCII。
* 其编码范围是0x00-0xFF,0x00-0x7F之间完全和ASCII一致,0x80-0x9F之间是控制字符,0xA0-0xFF之间是文字符号。
*/
@Native
static final byte LATIN1 = 0;
@Native
static final byte UTF16 = 1;
/**
* The value is used for character storage.
*
* @implNote This field is trusted by the VM, and is a subject to constant folding if String instance is constant.
* Overwriting this field after construction will cause problems.
*
* Additionally, it is marked with {@link Stable} to trust the contents of the array.
* No other facility in JDK provides this functionality (yet).
* {@link Stable} is safe here, because value is never null.
*/
/*
* 以字节形式存储String中的char,即存储码元
*
* 如果是纯英文字符,则采用压缩存储,一个byte代表一个char。
* 出现汉字等符号后,汉字可占多个byte,且一个英文字符也将占有2个byte。
*
* windows上使用小端法存字符串。
* 如果输入是:String s = "\u56DB\u6761\uD869\uDEA5"; // "四条𪚥","𪚥"在UTF16中占4个字节
* 则value中存储(十六进制):[DB, 56, 61, 67, 69, D8, A5, DE]
*/
@Stable
private final byte[] value;
/**
* The identifier of the encoding used to encode the bytes in {@code value}. The supported values in this implementation are LATIN1 and UTF16。
*
* @implNote This field is trusted by the VM, and is a subject to constant folding if String instance is constant.
* Overwriting this field after construction will cause problems.
*/
// 当前字符串的编码:LATIN1(0)或UTF16(1)
private final byte coder;
/**
* Cache the hash code for the string
*/
// 当前字符串哈希码,初始值默认为0
private int hash; // Default to 0
static {
/*
* 默认情形下,虚拟机会开启“紧凑字符串”选项,即令COMPACT_STRINGS = true。
* 可以在虚拟机参数上设置-XX:-CompactStrings来关闭“紧凑字符串”选项。
* 如果COMPACT_STRINGS == true,则String会有LATIN1或UTF16两种存储形式。否则,只使用UTF16形式。
*/
COMPACT_STRINGS = true;
}
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Initializes a newly created {@code String} object so that it represents an empty character sequence.
* Note that use of this constructor is unnecessary since Strings are immutable.
*/
// ▶ 0 构造空串
public String() {
this.value = "".value;
this.coder = "".coder;
}
/**
* Package private constructor which shares value array for speed.
*/
// ▶ 1 构造包含指定字节序列和字符串编码的String
String(byte[] value, byte coder) {
this.value = value;
this.coder = coder;
}
/**
* Initializes a newly created {@code String} object so that it represents the same sequence of characters as the argument;
* in other words, the newly created string is a copy of the argument string. Unless an explicit copy of {@code original} is needed,
* use of this constructor is unnecessary since Strings are immutable.
*
* @param original A {@code String}
*/
// ▶ 2 构造String的副本(哈希值都一样)
@HotSpotIntrinsicCandidate
public String(String original) {
this.value = original.value;
this.coder = original.coder;
this.hash = original.hash;
}
/**
* Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.
* The contents of the string buffer are copied; subsequent modification of the string buffer does not affect the newly created string.
*
* @param buffer A {@code StringBuffer}
*/
// ▶ 2-1 构造与buffer内容完全一致的字符串(哈希值都一样)
public String(StringBuffer buffer) {
this(buffer.toString());
}
/**
* Package private constructor.
* Trailing Void argument is there for disambiguating it against other (public) constructors.
*
* Stores the char[] value into a byte[] that each byte represents the8 low-order bits of the corresponding character,
* if the char[] contains only latin1 character.
* Or a byte[] that stores all characters in their byte sequences defined by the {@code StringUTF16}.
*/
// ▶ 3 将指定范围的char序列打包成String。参数sig仅用作占位,以消除与构造器<3-2>的歧义
String(char[] value, int off, int len, Void sig) {
// 空串
if(len == 0) {
this.value = "".value;
this.coder = "".coder;
return;
}
// 允许对字符串压缩存储
if(COMPACT_STRINGS) {
// 将UTF16-String内部的字节转换为LATIN1-String内部的字节
byte[] val = StringUTF16.compress(value, off, len);
if(val != null) {
this.value = val;
this.coder = LATIN1;
return;
}
}
this.coder = UTF16;
// 将value中的char批量转换为UTF16-String内部的字节,并返回
this.value = StringUTF16.toBytes(value, off, len);
}
/**
* Allocates a new {@code String} so that it represents the sequence of characters currently contained in the character array argument.
* The contents of the character array are copied; subsequent modification of the character array does not affect the newly created string.
*
* @param value The initial value of the string
*/
// ▶ 3-1 将指定的char序列打包成String。
public String(char value[]) {
this(value, 0, value.length, null);
}
/**
* Allocates a new {@code String} that contains characters from a subarray of the character array argument.
* The {@code offset} argument is the index of the first character of the subarray and the {@code count} argument specifies the length of the subarray.
* The contents of the subarray are copied; subsequent modification of the character array does not affect the newly created string.
*
* @param value Array that is the source of characters
* @param offset The initial offset
* @param count The length
*
* @throws IndexOutOfBoundsException If {@code offset} is negative, {@code count} is negative, or {@code offset} is greater than {@code value.length - count}
*/
// ▶ 3-2 将指定范围的char序列打包成String。加入越界检查
public String(char value[], int offset, int count) {
this(value, offset, count, rangeCheck(value, offset, count));
}
/**
* Constructs a new {@code String} by decoding the specified subarray of bytes using the platform's default charset.
* The length of the new {@code String} is a function of the charset, and hence may not be equal to the length of the subarray.
*
* The behavior of this constructor when the given bytes are not valid in the default charset is unspecified.
* The {@link java.nio.charset.CharsetDecoder} class should be used when more control over the decoding process is required.
*
* @param bytes The bytes to be decoded into characters
* @param offset The index of the first byte to decode
* @param length The number of bytes to decode
*
* @throws IndexOutOfBoundsException If {@code offset} is negative, {@code length} is negative,
* or {@code offset} is greater than {@code bytes.length - length}
* @since 1.1
*/
// ▶ 4 按JVM默认字符集格式解码指定范围的字节序列,进而构造String
public String(byte bytes[], int offset, int length) {
checkBoundsOffCount(offset, length, bytes.length);
// 以JVM默认字符集格式解码byte[],返回结果集
StringCoding.Result ret = StringCoding.decode(bytes, offset, length);
this.value = ret.value;
this.coder = ret.coder;
}
/**
* Constructs a new {@code String} by decoding the specified array of bytes using the platform's default charset.
* The length of the new {@code String} is a function of the charset, and hence may not be equal to the length of the byte array.
*
* <p> The behavior of this constructor when the given bytes are not valid
* in the default charset is unspecified.
* The {@link java.nio.charset.CharsetDecoder} class should be used when more control over the decoding process is required.
*
* @param bytes The bytes to be decoded into characters
*
* @since 1.1
*/
// ▶ 4-1 按JVM默认字符集格式解码指定的字节序列,进而构造String
public String(byte[] bytes) {
this(bytes, 0, bytes.length);
}
/**
* Constructs a new {@code String} by decoding the specified subarray of bytes using the specified charset.
* The length of the new {@code String} is a function of the charset, and hence may not be equal to the length of the subarray.
*
* <p> The behavior of this constructor when the given bytes are not valid in the given charset is unspecified.
* The {@link java.nio.charset.CharsetDecoder} class should be used when more control over the decoding process is required.
*
* @param bytes The bytes to be decoded into characters
* @param offset The index of the first byte to decode
* @param length The number of bytes to decode
* @param charsetName The name of a supported {@linkplain Charset charset}
*
* @throws UnsupportedEncodingException If the named charset is not supported
* @throws IndexOutOfBoundsException If {@code offset} is negative, {@code length} is negative,
* or {@code offset} is greater than {@code bytes.length - length}
* @since 1.1
*/
// ▶ 5 按charsetName格式解码指定范围的字节序列,进而构造String
public String(byte bytes[], int offset, int length, String charsetName) throws UnsupportedEncodingException {
if(charsetName == null)
throw new NullPointerException("charsetName");
checkBoundsOffCount(offset, length, bytes.length);
// 以charsetName格式解析byte[],返回结果集
StringCoding.Result ret = StringCoding.decode(charsetName, bytes, offset, length);
this.value = ret.value;
this.coder = ret.coder;
}
/**
* Constructs a new {@code String} by decoding the specified array of bytes using the specified {@linkplain Charset charset}.
* The length of the new {@code String} is a function of the charset, and hence may not be equal to the length of the byte array.
*
* <p> The behavior of this constructor when the given bytes are not valid
* in the given charset is unspecified.
* The {@link java.nio.charset.CharsetDecoder} class should be used when more control over the decoding process is required.
*
* @param bytes The bytes to be decoded into characters
* @param charsetName The name of a supported {@linkplain Charset charset}
*
* @throws UnsupportedEncodingException If the named charset is not supported
* @since 1.1
*/
// ▶ 5-1 按charsetName格式解码指定的字节序列,进而构造String
public String(byte bytes[], String charsetName) throws UnsupportedEncodingException {
this(bytes, 0, bytes.length, charsetName);
}
/**
* Constructs a new {@code String} by decoding the specified subarray of bytes using the specified {@linkplain Charset charset}.
* The length of the new {@code String} is a function of the charset, and hence may not be equal to the length of the subarray.
*
* <p> This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement string.
* The {@link java.nio.charset.CharsetDecoder} class should be used when more control over the decoding process is required.
*
* @param bytes The bytes to be decoded into characters
* @param offset The index of the first byte to decode
* @param length The number of bytes to decode
* @param charset The {@linkplain Charset charset} to be used to decode the {@code bytes}
*
* @throws IndexOutOfBoundsException If {@code offset} is negative, {@code length} is negative,
* or {@code offset} is greater than {@code bytes.length - length}
* @since 1.6
*/
// ▶ 6 按charset格式解码解码指定范围的字节序列,返回解码后的字符序列
public String(byte bytes[], int offset, int length, Charset charset) {
if(charset == null)
throw new NullPointerException("charset");
checkBoundsOffCount(offset, length, bytes.length);
// 以charset格式解码byte[],返回结果集
StringCoding.Result ret = StringCoding.decode(charset, bytes, offset, length);
this.value = ret.value;
this.coder = ret.coder;
}
/**
* Constructs a new {@code String} by decoding the specified array of bytes using the specified {@linkplain Charset charset}.
* The length of the new {@code String} is a function of the charset, and hence may not be equal to the length of the byte array.
*
* <p> This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement string.
* The {@link java.nio.charset.CharsetDecoder} class should be used when more control over the decoding process is required.
*
* @param bytes The bytes to be decoded into characters
* @param charset The {@linkplain Charset charset} to be used to decode the {@code bytes}
*
* @since 1.6
*/
// ▶ 6-1 按charset格式解码指定的字节序列,返回解码后的字符序列
public String(byte bytes[], Charset charset) {
this(bytes, 0, bytes.length, charset);
}
/**
* Package private constructor. Trailing Void argument is there for
* disambiguating it against other (public) constructors.
*/
// ▶ 7 按照字符序列asb内部的字节序列构造String。参数sig仅用作占位,以消除与构造器<7-1>的歧义
String(AbstractStringBuilder asb, Void sig) {
byte[] val = asb.getValue();
int length = asb.length();
if(asb.isLatin1()) {
this.coder = LATIN1;
this.value = Arrays.copyOfRange(val, 0, length);
} else {
if(COMPACT_STRINGS) {
// 将UTF16-String内部的字节转换为LATIN1-String内部的字节后,再返回
byte[] buf = StringUTF16.compress(val, 0, length);
if(buf != null) {
this.coder = LATIN1;
this.value = buf;
return;
}
}
this.coder = UTF16;
this.value = Arrays.copyOfRange(val, 0, length << 1);
}
}
/**
* Allocates a new string that contains the sequence of characters currently contained in the string builder argument.
* The contents of the string builder are copied; subsequent modification of the string builder does not affect the newly created string.
*
* <p> This constructor is provided to ease migration to {@code
* StringBuilder}. Obtaining a string from a string builder via the {@code toString} method is likely to run faster and is generally preferred.
*
* @param builder A {@code StringBuilder}
*
* @since 1.5
*/
// ▶ 7-1 按照字符序列builder内部的字节序列构造String
public String(StringBuilder builder) {
this(builder, null);
}
/**
* Allocates a new {@code String} that contains characters from a subarray of the <a href="Character.html#unicode">Unicode code point</a> array argument.
* The {@code offset} argument is the index of the first code point of the subarray and the {@code count} argument specifies the length of the subarray.
* The contents of the subarray are converted to {@code char}s; subsequent modification of the {@code int} array does not affect the newly created string.
*
* @param codePoints Array that is the source of Unicode code points
* @param offset The initial offset
* @param count The length
*
* @throws IllegalArgumentException If any invalid Unicode code point is found in {@code codePoints}
* @throws IndexOutOfBoundsException If {@code offset} is negative, {@code count} is negative,
* or {@code offset} is greater than {@code codePoints.length - count}
* @since 1.5
*/
// ▶ 8 将codePoints中的一组Unicode值转换为UTF16编码值,再以字节形式存入String(大小端由系统环境决定)
public String(int[] codePoints, int offset, int count) {
// 范围检查
checkBoundsOffCount(offset, count, codePoints.length);
// 空串
if(count == 0) {
this.value = "".value;
this.coder = "".coder;
return;
}
// 可压缩的字符串
if(COMPACT_STRINGS) {
// 将codePoints中的一组Unicode值批量转换为LATIN1-String内部的字节,再返回
byte[] val = StringLatin1.toBytes(codePoints, offset, count);
if(val != null) {
this.coder = LATIN1;
this.value = val;
return;
}
}
this.coder = UTF16;
// 将codePoints中的一组Unicode值批量转换为UTF16-String内部的字节,再返回
this.value = StringUTF16.toBytes(codePoints, offset, count);
}
/**
* Allocates a new {@code String} constructed from a subarray of an array of 8-bit integer values.
*
* <p> The {@code offset} argument is the index of the first byte of the
* subarray, and the {@code count} argument specifies the length of the subarray.
*
* <p> Each {@code byte} in the subarray is converted to a {@code char} as
* specified in the {@link #String(byte[], int) String(byte[],int)} constructor.
*
* @param ascii The bytes to be converted to characters
* @param hibyte The top 8 bits of each 16-bit Unicode code unit
* @param offset The initial offset
* @param count The length
*
* @throws IndexOutOfBoundsException If {@code offset} is negative, {@code count} is negative,
* or {@code offset} is greater than {@code ascii.length - count}
* @see #String(byte[], int)
* @see #String(byte[], int, int, String)
* @see #String(byte[], int, int, Charset)
* @see #String(byte[], int, int)
* @see #String(byte[], String)
* @see #String(byte[], Charset)
* @see #String(byte[])
*
* @deprecated This method does not properly convert bytes into characters.
* As of JDK 1.1, the preferred way to do this is via the {@code String} constructors that take a {@link Charset},
* charset name, or that use the platform's default charset.
*/
// ▶ 9 ※ 过时
@Deprecated(since = "1.1")
public String(byte ascii[], int hibyte, int offset, int count) {
checkBoundsOffCount(offset, count, ascii.length);
if(count == 0) {
this.value = "".value;
this.coder = "".coder;
return;
}
if(COMPACT_STRINGS && (byte) hibyte == 0) {
this.value = Arrays.copyOfRange(ascii, offset, offset + count);
this.coder = LATIN1;
} else {
hibyte <<= 8;
// 创建长度为2*len的字节数组
byte[] val = StringUTF16.newBytesFor(count);
for(int i = 0; i < count; i++) {
// 将形参三的两个低字节转换为UTF16-String内部的字节,存入val
StringUTF16.putChar(val, i, hibyte | (ascii[offset++] & 0xff));
}
this.value = val;
this.coder = UTF16;
}
}
/**
* Allocates a new {@code String} containing characters constructed from an array of 8-bit integer values.
* Each character <i>c</i> in the resulting string is constructed from the corresponding component
* <i>b</i> in the byte array such that:
*
* <blockquote><pre>
* <b><i>c</i></b> == (char)(((hibyte & 0xff) << 8)
* | (<b><i>b</i></b> & 0xff))
* </pre></blockquote>
*
* @param ascii The bytes to be converted to characters
* @param hibyte The top 8 bits of each 16-bit Unicode code unit
*
* @see #String(byte[], int, int, String)
* @see #String(byte[], int, int, Charset)
* @see #String(byte[], int, int)
* @see #String(byte[], String)
* @see #String(byte[], Charset)
* @see #String(byte[])
* @deprecated This method does not properly convert bytes into characters.
* As of JDK 1.1, the preferred way to do this is via the {@code String} constructors that take a {@link Charset},
* charset name, or that use the platform's default charset.
*/
// ▶ 9-1 ※ 过时
@Deprecated(since = "1.1")
public String(byte ascii[], int hibyte) {
this(ascii, hibyte, 0, ascii.length);
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 获取byte/byte[] ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Encodes this {@code String} into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
*
* <p> The behavior of this method when this string cannot be encoded in the default charset is unspecified.
* The {@link java.nio.charset.CharsetEncoder} class should be used when more control over the encoding process is required.
*
* @return The resultant byte array
*
* @since 1.1
*/
// 编码String,返回JVM默认字符集格式的byte[]
public byte[] getBytes() {
// coder指示了String是LATIN1-String还是UTF16-string。
return StringCoding.encode(coder(), value);
}
/**
* Encodes this {@code String} into a sequence of bytes using the named charset, storing the result into a new byte array.
*
* <p> The behavior of this method when this string cannot be encoded in the given charset is unspecified.
* The {@link java.nio.charset.CharsetEncoder} class should be used when more control over the encoding process is required.
*
* @param charsetName The name of a supported {@linkplain Charset charset}
*
* @return The resultant byte array
*
* @throws UnsupportedEncodingException If the named charset is not supported
* @since 1.1
*/
// 编码String,返回charsetName字符集格式的byte[]
public byte[] getBytes(String charsetName) throws UnsupportedEncodingException {
if(charsetName == null)
throw new NullPointerException();
// coder指示了String是LATIN1-String还是UTF16-string。
return StringCoding.encode(charsetName, coder(), value);
}
/**
* Encodes this {@code String} into a sequence of bytes using the given {@linkplain Charset charset}, storing the result into a new byte array.
*
* <p> This method always replaces malformed-input and unmappable-character sequences with this charset's default replacement byte array.
* The {@link java.nio.charset.CharsetEncoder} class should be used when more control over the encoding process is required.
*
* @param charset The {@linkplain Charset} to be used to encode the {@code String}
*
* @return The resultant byte array
*
* @since 1.6
*/
// 编码String,返回charset字符集格式的byte[]
public byte[] getBytes(Charset charset) {
if(charset == null)
throw new NullPointerException();
// coder指示了String是LATIN1-String还是UTF16-string。
return StringCoding.encode(charset, coder(), value);
}
/**
* Copies characters from this string into the destination byte array.
* Each byte receives the 8 low-order bits of the corresponding character.
* The eight high-order bits of each character are not copied and do not participate in the transfer in any way.
*
* The first character to be copied is at index {@code srcBegin}; the last character to be copied is at index {@code srcEnd-1}.
* The total number of characters to be copied is {@code srcEnd-srcBegin}.
* The characters, converted to bytes, are copied into the subarray of {@code dst} starting at index {@code dstBegin} and ending at index:
*
* <blockquote><pre>
* dstBegin + (srcEnd-srcBegin) - 1
* </pre></blockquote>
*
* @param srcBegin Index of the first character in the string to copy
* @param srcEnd Index after the last character in the string to copy
* @param dst The destination array
* @param dstBegin The start offset in the destination array
*
* @throws IndexOutOfBoundsException If any of the following is true:
* <ul>
* <li> {@code srcBegin} is negative
* <li> {@code srcBegin} is greater than {@code srcEnd}
* <li> {@code srcEnd} is greater than the length of this String
* <li> {@code dstBegin} is negative
* <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
* dst.length}
* </ul>
* @deprecated This method does not properly convert characters into bytes.
* As of JDK 1.1, the preferred way to do this is via the {@link #getBytes()} method, which uses the platform's default charset.
*
* ※ 已过时,设计有缺陷
*
* 编码String,只保留原char中的低byte。
* 这意味着,只能正确处理[0x00, 0xFF]范围内的字符,对于超出范围的字节,则将其抛弃。
*
* 例如:
* byte[] value = new byte[4]{0x12,0x34, 0x56,0x78};
* byte[] dst = new byte[4];
* s.getBytes(value, 0, 2, dst, 0); // 字节数组dst:[34, 78]
*
* 只有原字节对表示的char在[0x00, 0xFF]范围内,才能得到一个正确的压缩
*/
// ※ 已过时,设计有缺陷
@Deprecated(since = "1.1")
public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
checkBoundsBeginEnd(srcBegin, srcEnd, length());
Objects.requireNonNull(dst);
checkBoundsOffCount(dstBegin, srcEnd - srcBegin, dst.length);
if(isLatin1()) {
// 将LATIN1-String内部的字节转换为LATIN1-String内部的字节
StringLatin1.getBytes(value, srcBegin, srcEnd, dst, dstBegin);
} else {
// 将UTF16-String内部的字节转换为LATIN1-String内部的字节
StringUTF16.getBytes(value, srcBegin, srcEnd, dst, dstBegin);
}
}
/*▲ 获取byte/byte[] ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 获取char/char[] ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns the {@code char} value at the specified index.
* An index ranges from {@code 0} to {@code length() - 1}.
* The first {@code char} value of the sequence is at index {@code 0}, the next at index {@code 1}, and so on, as for array indexing.
*
* If the {@code char} value specified by the index is a <a href="Character.html#unicode">surrogate</a>, the surrogate value is returned.
*
* @param index the index of the {@code char} value.
*
* @return the {@code char} value at the specified index of this string. The first {@code char} value is at index {@code 0}.
*
* @throws IndexOutOfBoundsException if the {@code index} argument is negative or not less than the length of this string.
*/
// 将String内部的字节转换为char后返回
public char charAt(int index) {
// 可以用压缩的Latin1字符集表示
if(isLatin1()) {
// 将LATIN1-String内部的字节转换为char后返回
return StringLatin1.charAt(value, index);
} else {
// 将UTF16-String内部的字节转换为char后返回
return StringUTF16.charAt(value, index);
}
}
/**
* Copies characters from this string into the destination character array.
* <p>
* The first character to be copied is at index {@code srcBegin}; the last character to be copied is at index {@code srcEnd-1}
* (thus the total number of characters to be copied is {@code srcEnd-srcBegin}).
* The characters are copied into the subarray of {@code dst} starting at index {@code dstBegin} and ending at index:
* <blockquote><pre>
* dstBegin + (srcEnd-srcBegin) - 1
* </pre></blockquote>
*
* @param srcBegin index of the first character in the string to copy.
* @param srcEnd index after the last character in the string to copy.
* @param dst the destination array.
* @param dstBegin the start offset in the destination array.
*
* @throws IndexOutOfBoundsException If any of the following is true:
* <ul><li>{@code srcBegin} is negative.
* <li>{@code srcBegin} is greater than {@code srcEnd}
* <li>{@code srcEnd} is greater than the length of this
* string
* <li>{@code dstBegin} is negative
* <li>{@code dstBegin+(srcEnd-srcBegin)} is larger than
* {@code dst.length}</ul>
*/
// 将String内部的字节批量转换为char后存入dst
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
checkBoundsBeginEnd(srcBegin, srcEnd, length());
checkBoundsOffCount(dstBegin, srcEnd - srcBegin, dst.length);
// 可以用压缩的Latin1字符集表示
if(isLatin1()) {
// 将LATIN1-String内部的字节批量转换为char后存入dst
StringLatin1.getChars(value, srcBegin, srcEnd, dst, dstBegin);
} else {
// 将UTF16-String内部的字节批量转换为char后存入dst
StringUTF16.getChars(value, srcBegin, srcEnd, dst, dstBegin);
}
}
/**
* Converts this string to a new character array.
*
* @return a newly allocated character array whose length is the length of this string
* and whose contents are initialized to contain the character sequence represented by this string.
*/
// 将当前字符串的存储形式转换为char[]
public char[] toCharArray() {
return isLatin1()
? StringLatin1.toChars(value) // 将LATIN1-String内部的字节全部转换为char后返回
: StringUTF16.toChars(value); // 将UTF16-String内部的字节全部转换为char后返回
}
/*▲ 获取char/char[] ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 字符串化 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns the string representation of the {@code boolean} argument.
*
* @param b a {@code boolean}.
*
* @return if the argument is {@code true}, a string equal to {@code "true"} is returned;
* otherwise, a string equal to {@code "false"} is returned.
*/
public static String valueOf(boolean b) {
return b ? "true" : "false";
}
/**
* Returns the string representation of the {@code char} argument.
*
* @param c a {@code char}.
*
* @return a string of length {@code 1} containing as its single character the argument {@code c}.
*/
public static String valueOf(char c) {
// 将char转换为LATIN1-String内部的字节,并返回
if(COMPACT_STRINGS && StringLatin1.canEncode(c)) {
return new String(StringLatin1.toBytes(c), LATIN1);
}
// 将char转换为UTF16-String内部的字节,并返回
return new String(StringUTF16.toBytes(c), UTF16);
}
/**
* Returns the string representation of the {@code int} argument.
* <p>
* The representation is exactly the one returned by the {@code Integer.toString} method of one argument.
*
* @param i an {@code int}.
*
* @return a string representation of the {@code int} argument.
*
* @see Integer#toString(int, int)
*/
public static String valueOf(int i) {
return Integer.toString(i);
}
/**
* Returns the string representation of the {@code long} argument.
* <p>
* The representation is exactly the one returned by the {@code Long.toString} method of one argument.
*
* @param l a {@code long}.
*
* @return a string representation of the {@code long} argument.
*
* @see Long#toString(long)
*/
public static String valueOf(long l) {
return Long.toString(l);
}
/**
* Returns the string representation of the {@code float} argument.
* <p>
* The representation is exactly the one returned by the {@code Float.toString} method of one argument.
*
* @param f a {@code float}.
*
* @return a string representation of the {@code float} argument.
*
* @see Float#toString(float)
*/
public static String valueOf(float f) {
return Float.toString(f);
}
/**
* Returns the string representation of the {@code double} argument.
* <p>
* The representation is exactly the one returned by the {@code Double.toString} method of one argument.
*
* @param d a {@code double}.
*
* @return a string representation of the {@code double} argument.
*
* @see Double#toString(double)
*/
public static String valueOf(double d) {
return Double.toString(d);
}
/**
* Returns the string representation of the {@code Object} argument.
*
* @param obj an {@code Object}.
*
* @return if the argument is {@code null}, then a string equal to {@code "null"};
* otherwise, the value of {@code obj.toString()} is returned.
*
* @see Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
/**
* Returns the string representation of the {@code char} array argument.
* The contents of the character array are copied;
* subsequent modification of the character array does not affect the returned string.
*
* @param data the character array.
*
* @return a {@code String} that contains the characters of the character array.
*/
public static String valueOf(char data[]) {
return new String(data);
}
/**
* Returns the string representation of a specific subarray of the {@code char} array argument.
* <p>
* The {@code offset} argument is the index of the first character of the subarray.
* The {@code count} argument specifies the length of the subarray.
* The contents of the subarray are copied; subsequent modification of the character array does not affect the returned string.
*
* @param data the character array.
* @param offset initial offset of the subarray.
* @param count length of the subarray.
*
* @return a {@code String} that contains the characters of the specified subarray of the character array.
*
* @throws IndexOutOfBoundsException if {@code offset} is negative,
* or {@code count} is negative, or {@code offset+count} is larger than {@code data.length}.
*/
public static String valueOf(char data[], int offset, int count) {
return new String(data, offset, count);
}
/**
* Equivalent to {@link #valueOf(char[])}.