java中charsequence_String详解, String和CharSequence区别, StringBuilder和StringBuffer的区别 (String系列之1)...

1 packagejava.lang;2

3 importjava.io.ObjectStreamField;4 importjava.io.UnsupportedEncodingException;5 importjava.nio.charset.Charset;6 importjava.util.ArrayList;7 importjava.util.Arrays;8 importjava.util.Comparator;9 importjava.util.Formatter;10 importjava.util.Locale;11 importjava.util.regex.Matcher;12 importjava.util.regex.Pattern;13 importjava.util.regex.PatternSyntaxException;14

15 public final classString16 implements java.io.Serializable, Comparable, CharSequence {17 private final charvalue[];18

19 private inthash;20

21 private static final long serialVersionUID = -6849794470754667710L;22

23 private static final ObjectStreamField[] serialPersistentFields =

24 new ObjectStreamField[0];25

26 publicString() {27 this.value = new char[0];28 }29

30 publicString(String original) {31 this.value =original.value;32 this.hash =original.hash;33 }34

35 public String(charvalue[]) {36 this.value =Arrays.copyOf(value, value.length);37 }38

39 public String(char value[], int offset, intcount) {40 if (offset < 0) {41 throw newStringIndexOutOfBoundsException(offset);42 }43 if (count < 0) {44 throw newStringIndexOutOfBoundsException(count);45 }46 //Note: offset or count might be near -1>>>1.

47 if (offset > value.length -count) {48 throw new StringIndexOutOfBoundsException(offset +count);49 }50 this.value = Arrays.copyOfRange(value, offset, offset+count);51 }52

53 public String(int[] codePoints, int offset, intcount) {54 if (offset < 0) {55 throw newStringIndexOutOfBoundsException(offset);56 }57 if (count < 0) {58 throw newStringIndexOutOfBoundsException(count);59 }60 //Note: offset or count might be near -1>>>1.

61 if (offset > codePoints.length -count) {62 throw new StringIndexOutOfBoundsException(offset +count);63 }64

65 final int end = offset +count;66

67 //Pass 1: Compute precise size of char[]

68 int n =count;69 for (int i = offset; i < end; i++) {70 int c =codePoints[i];71 if(Character.isBmpCodePoint(c))72 continue;73 else if(Character.isValidCodePoint(c))74 n++;75 else throw newIllegalArgumentException(Integer.toString(c));76 }77

78 //Pass 2: Allocate and fill in char[]

79 final char[] v = new char[n];80

81 for (int i = offset, j = 0; i < end; i++, j++) {82 int c =codePoints[i];83 if(Character.isBmpCodePoint(c))84 v[j] = (char)c;85 else

86 Character.toSurrogates(c, v, j++);87 }88

89 this.value =v;90 }91

92 @Deprecated93 public String(byte ascii[], int hibyte, int offset, intcount) {94 checkBounds(ascii, offset, count);95 char value[] = new char[count];96

97 if (hibyte == 0) {98 for (int i = count; i-- > 0;) {99 value[i] = (char)(ascii[i + offset] & 0xff);100 }101 } else{102 hibyte <<= 8;103 for (int i = count; i-- > 0;) {104 value[i] = (char)(hibyte | (ascii[i + offset] & 0xff));105 }106 }107 this.value =value;108 }109

110 @Deprecated111 public String(byte ascii[], inthibyte) {112 this(ascii, hibyte, 0, ascii.length);113 }114

115 private static void checkBounds(byte[] bytes, int offset, intlength) {116 if (length < 0)117 throw newStringIndexOutOfBoundsException(length);118 if (offset < 0)119 throw newStringIndexOutOfBoundsException(offset);120 if (offset > bytes.length -length)121 throw new StringIndexOutOfBoundsException(offset +length);122 }123

124 public String(byte bytes[], int offset, intlength, String charsetName)125 throwsUnsupportedEncodingException {126 if (charsetName == null)127 throw new NullPointerException("charsetName");128 checkBounds(bytes, offset, length);129 this.value =StringCoding.decode(charsetName, bytes, offset, length);130 }131

132 public String(byte bytes[], int offset, intlength, Charset charset) {133 if (charset == null)134 throw new NullPointerException("charset");135 checkBounds(bytes, offset, length);136 this.value =StringCoding.decode(charset, bytes, offset, length);137 }138

139 public String(bytebytes[], String charsetName)140 throwsUnsupportedEncodingException {141 this(bytes, 0, bytes.length, charsetName);142 }143

144 public String(bytebytes[], Charset charset) {145 this(bytes, 0, bytes.length, charset);146 }147

148 public String(byte bytes[], int offset, intlength) {149 checkBounds(bytes, offset, length);150 this.value =StringCoding.decode(bytes, offset, length);151 }152

153 public String(bytebytes[]) {154 this(bytes, 0, bytes.length);155 }156

157 publicString(StringBuffer buffer) {158 synchronized(buffer) {159 this.value =Arrays.copyOf(buffer.getValue(), buffer.length());160 }161 }162

163 publicString(StringBuilder builder) {164 this.value =Arrays.copyOf(builder.getValue(), builder.length());165 }166

167 String(char[] value, booleanshare) {168 //assert share : "unshared not supported";

169 this.value =value;170 }171

172 @Deprecated173 String(int offset, int count, char[] value) {174 this(value, offset, count);175 }176

177 public intlength() {178 returnvalue.length;179 }180

181 public booleanisEmpty() {182 return value.length == 0;183 }184

185 public char charAt(intindex) {186 if ((index < 0) || (index >=value.length)) {187 throw newStringIndexOutOfBoundsException(index);188 }189 returnvalue[index];190 }191

192 public int codePointAt(intindex) {193 if ((index < 0) || (index >=value.length)) {194 throw newStringIndexOutOfBoundsException(index);195 }196 returnCharacter.codePointAtImpl(value, index, value.length);197 }198

199 public int codePointBefore(intindex) {200 int i = index - 1;201 if ((i < 0) || (i >=value.length)) {202 throw newStringIndexOutOfBoundsException(index);203 }204 return Character.codePointBeforeImpl(value, index, 0);205 }206

207 public int codePointCount(int beginIndex, intendIndex) {208 if (beginIndex < 0 || endIndex > value.length || beginIndex >endIndex) {209 throw newIndexOutOfBoundsException();210 }211 return Character.codePointCountImpl(value, beginIndex, endIndex -beginIndex);212 }213

214 public int offsetByCodePoints(int index, intcodePointOffset) {215 if (index < 0 || index >value.length) {216 throw newIndexOutOfBoundsException();217 }218 return Character.offsetByCodePointsImpl(value, 0, value.length,219 index, codePointOffset);220 }221

222 void getChars(char dst[], intdstBegin) {223 System.arraycopy(value, 0, dst, dstBegin, value.length);224 }225

226 public void getChars(int srcBegin, int srcEnd, char dst[], intdstBegin) {227 if (srcBegin < 0) {228 throw newStringIndexOutOfBoundsException(srcBegin);229 }230 if (srcEnd >value.length) {231 throw newStringIndexOutOfBoundsException(srcEnd);232 }233 if (srcBegin >srcEnd) {234 throw new StringIndexOutOfBoundsException(srcEnd -srcBegin);235 }236 System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd -srcBegin);237 }238

239 @Deprecated240 public void getBytes(int srcBegin, int srcEnd, byte dst[], intdstBegin) {241 if (srcBegin < 0) {242 throw newStringIndexOutOfBoundsException(srcBegin);243 }244 if (srcEnd >value.length) {245 throw newStringIndexOutOfBoundsException(srcEnd);246 }247 if (srcBegin >srcEnd) {248 throw new StringIndexOutOfBoundsException(srcEnd -srcBegin);249 }250 int j =dstBegin;251 int n =srcEnd;252 int i =srcBegin;253 char[] val = value; /*avoid getfield opcode*/

254

255 while (i

260 public byte[] getBytes(String charsetName)261 throwsUnsupportedEncodingException {262 if (charsetName == null) throw newNullPointerException();263 return StringCoding.encode(charsetName, value, 0, value.length);264 }265

266 public byte[] getBytes(Charset charset) {267 if (charset == null) throw newNullPointerException();268 return StringCoding.encode(charset, value, 0, value.length);269 }270

271 public byte[] getBytes() {272 return StringCoding.encode(value, 0, value.length);273 }274

275 public booleanequals(Object anObject) {276 if (this ==anObject) {277 return true;278 }279 if (anObject instanceofString) {280 String anotherString =(String) anObject;281 int n =value.length;282 if (n ==anotherString.value.length) {283 char v1[] =value;284 char v2[] =anotherString.value;285 int i = 0;286 while (n-- != 0) {287 if (v1[i] !=v2[i])288 return false;289 i++;290 }291 return true;292 }293 }294 return false;295 }296

297 public booleancontentEquals(StringBuffer sb) {298 synchronized(sb) {299 returncontentEquals((CharSequence) sb);300 }301 }302

303 public booleancontentEquals(CharSequence cs) {304 if (value.length !=cs.length())305 return false;306 //Argument is a StringBuffer, StringBuilder

307 if (cs instanceofAbstractStringBuilder) {308 char v1[] =value;309 char v2[] =((AbstractStringBuilder) cs).getValue();310 int i = 0;311 int n =value.length;312 while (n-- != 0) {313 if (v1[i] !=v2[i])314 return false;315 i++;316 }317 return true;318 }319 //Argument is a String

320 if (cs.equals(this))321 return true;322 //Argument is a generic CharSequence

323 char v1[] =value;324 int i = 0;325 int n =value.length;326 while (n-- != 0) {327 if (v1[i] !=cs.charAt(i))328 return false;329 i++;330 }331 return true;332 }333

334 public booleanequalsIgnoreCase(String anotherString) {335 return (this == anotherString) ? true

336 : (anotherString != null)337 && (anotherString.value.length ==value.length)338 && regionMatches(true, 0, anotherString, 0, value.length);339 }340

341 public intcompareTo(String anotherString) {342 int len1 =value.length;343 int len2 =anotherString.value.length;344 int lim =Math.min(len1, len2);345 char v1[] =value;346 char v2[] =anotherString.value;347

348 int k = 0;349 while (k

360 public static final ComparatorCASE_INSENSITIVE_ORDER361 = newCaseInsensitiveComparator();362 private static classCaseInsensitiveComparator363 implements Comparator, java.io.Serializable {364 //use serialVersionUID from JDK 1.2.2 for interoperability

365 private static final long serialVersionUID = 8575799808933029326L;366

367 public intcompare(String s1, String s2) {368 int n1 =s1.length();369 int n2 =s2.length();370 int min =Math.min(n1, n2);371 for (int i = 0; i < min; i++) {372 char c1 =s1.charAt(i);373 char c2 =s2.charAt(i);374 if (c1 !=c2) {375 c1 =Character.toUpperCase(c1);376 c2 =Character.toUpperCase(c2);377 if (c1 !=c2) {378 c1 =Character.toLowerCase(c1);379 c2 =Character.toLowerCase(c2);380 if (c1 !=c2) {381 //No overflow because of numeric promotion

382 return c1 -c2;383 }384 }385 }386 }387 return n1 -n2;388 }389 }390

391 public intcompareToIgnoreCase(String str) {392 return CASE_INSENSITIVE_ORDER.compare(this, str);393 }394

395 public boolean regionMatches(int toffset, String other, intooffset,396 intlen) {397 char ta[] =value;398 int to =toffset;399 char pa[] =other.value;400 int po =ooffset;401 //Note: toffset, ooffset, or len might be near -1>>>1.

402 if ((ooffset < 0) || (toffset < 0)403 || (toffset > (long)value.length -len)404 || (ooffset > (long)other.value.length -len)) {405 return false;406 }407 while (len-- > 0) {408 if (ta[to++] != pa[po++]) {409 return false;410 }411 }412 return true;413 }414

415 public boolean regionMatches(boolean ignoreCase, inttoffset,416 String other, int ooffset, intlen) {417 char ta[] =value;418 int to =toffset;419 char pa[] =other.value;420 int po =ooffset;421 //Note: toffset, ooffset, or len might be near -1>>>1.

422 if ((ooffset < 0) || (toffset < 0)423 || (toffset > (long)value.length -len)424 || (ooffset > (long)other.value.length -len)) {425 return false;426 }427 while (len-- > 0) {428 char c1 = ta[to++];429 char c2 = pa[po++];430 if (c1 ==c2) {431 continue;432 }433 if(ignoreCase) {434 //If characters don't match but case may be ignored,435 //try converting both characters to uppercase.436 //If the results match, then the comparison scan should437 //continue.

438 char u1 =Character.toUpperCase(c1);439 char u2 =Character.toUpperCase(c2);440 if (u1 ==u2) {441 continue;442 }443 //Unfortunately, conversion to uppercase does not work properly444 //for the Georgian alphabet, which has strange rules about case445 //conversion. So we need to make one last check before446 //exiting.

447 if (Character.toLowerCase(u1) ==Character.toLowerCase(u2)) {448 continue;449 }450 }451 return false;452 }453 return true;454 }455

456 public boolean startsWith(String prefix, inttoffset) {457 char ta[] =value;458 int to =toffset;459 char pa[] =prefix.value;460 int po = 0;461 int pc =prefix.value.length;462 //Note: toffset might be near -1>>>1.

463 if ((toffset < 0) || (toffset > value.length -pc)) {464 return false;465 }466 while (--pc >= 0) {467 if (ta[to++] != pa[po++]) {468 return false;469 }470 }471 return true;472 }473

474 public booleanstartsWith(String prefix) {475 return startsWith(prefix, 0);476 }477

478 public booleanendsWith(String suffix) {479 return startsWith(suffix, value.length -suffix.value.length);480 }481

482 public inthashCode() {483 int h =hash;484 if (h == 0 && value.length > 0) {485 char val[] =value;486

487 for (int i = 0; i < value.length; i++) {488 h = 31 * h +val[i];489 }490 hash =h;491 }492 returnh;493 }494

495 public int indexOf(intch) {496 return indexOf(ch, 0);497 }498

499 public int indexOf(int ch, intfromIndex) {500 final int max =value.length;501 if (fromIndex < 0) {502 fromIndex = 0;503 } else if (fromIndex >=max) {504 //Note: fromIndex might be near -1>>>1.

505 return -1;506 }507

508 if (ch

511 final char[] value = this.value;512 for (int i = fromIndex; i < max; i++) {513 if (value[i] ==ch) {514 returni;515 }516 }517 return -1;518 } else{519 returnindexOfSupplementary(ch, fromIndex);520 }521 }522

523 private int indexOfSupplementary(int ch, intfromIndex) {524 if(Character.isValidCodePoint(ch)) {525 final char[] value = this.value;526 final char hi =Character.highSurrogate(ch);527 final char lo =Character.lowSurrogate(ch);528 final int max = value.length - 1;529 for (int i = fromIndex; i < max; i++) {530 if (value[i] == hi && value[i + 1] ==lo) {531 returni;532 }533 }534 }535 return -1;536 }537

538 public int lastIndexOf(intch) {539 return lastIndexOf(ch, value.length - 1);540 }541

542 public int lastIndexOf(int ch, intfromIndex) {543 if (ch

546 final char[] value = this.value;547 int i = Math.min(fromIndex, value.length - 1);548 for (; i >= 0; i--) {549 if (value[i] ==ch) {550 returni;551 }552 }553 return -1;554 } else{555 returnlastIndexOfSupplementary(ch, fromIndex);556 }557 }558

559 private int lastIndexOfSupplementary(int ch, intfromIndex) {560 if(Character.isValidCodePoint(ch)) {561 final char[] value = this.value;562 char hi =Character.highSurrogate(ch);563 char lo =Character.lowSurrogate(ch);564 int i = Math.min(fromIndex, value.length - 2);565 for (; i >= 0; i--) {566 if (value[i] == hi && value[i + 1] ==lo) {567 returni;568 }569 }570 }571 return -1;572 }573

574 public intindexOf(String str) {575 return indexOf(str, 0);576 }577

578 public int indexOf(String str, intfromIndex) {579 return indexOf(value, 0, value.length,580 str.value, 0, str.value.length, fromIndex);581 }582

583 static int indexOf(char[] source, int sourceOffset, intsourceCount,584 char[] target, int targetOffset, inttargetCount,585 intfromIndex) {586 if (fromIndex >=sourceCount) {587 return (targetCount == 0 ? sourceCount : -1);588 }589 if (fromIndex < 0) {590 fromIndex = 0;591 }592 if (targetCount == 0) {593 returnfromIndex;594 }595

596 char first =target[targetOffset];597 int max = sourceOffset + (sourceCount -targetCount);598

599 for (int i = sourceOffset + fromIndex; i <= max; i++) {600 /*Look for first character.*/

601 if (source[i] !=first) {602 while (++i <= max && source[i] !=first);603 }604

605 /*Found first character, now look at the rest of v2*/

606 if (i <=max) {607 int j = i + 1;608 int end = j + targetCount - 1;609 for (int k = targetOffset + 1; j < end &&source[j]610 == target[k]; j++, k++);611

612 if (j ==end) {613 /*Found whole string.*/

614 return i -sourceOffset;615 }616 }617 }618 return -1;619 }620

621 public intlastIndexOf(String str) {622 returnlastIndexOf(str, value.length);623 }624

625 public int lastIndexOf(String str, intfromIndex) {626 return lastIndexOf(value, 0, value.length,627 str.value, 0, str.value.length, fromIndex);628 }629

630 static int lastIndexOf(char[] source, int sourceOffset, intsourceCount,631 char[] target, int targetOffset, inttargetCount,632 intfromIndex) {633 /*

634 * Check arguments; return immediately where possible. For635 * consistency, don't check for null str.636 */

637 int rightIndex = sourceCount -targetCount;638 if (fromIndex < 0) {639 return -1;640 }641 if (fromIndex >rightIndex) {642 fromIndex =rightIndex;643 }644 /*Empty string always matches.*/

645 if (targetCount == 0) {646 returnfromIndex;647 }648

649 int strLastIndex = targetOffset + targetCount - 1;650 char strLastChar =target[strLastIndex];651 int min = sourceOffset + targetCount - 1;652 int i = min +fromIndex;653

654 startSearchForLastChar:655 while (true) {656 while (i >= min && source[i] !=strLastChar) {657 i--;658 }659 if (i

666 while (j >start) {667 if (source[j--] != target[k--]) {668 i--;669 continuestartSearchForLastChar;670 }671 }672 return start - sourceOffset + 1;673 }674 }675

676 public String substring(intbeginIndex) {677 if (beginIndex < 0) {678 throw newStringIndexOutOfBoundsException(beginIndex);679 }680 int subLen = value.length -beginIndex;681 if (subLen < 0) {682 throw newStringIndexOutOfBoundsException(subLen);683 }684 return (beginIndex == 0) ? this : newString(value, beginIndex, subLen);685 }686

687 public String substring(int beginIndex, intendIndex) {688 if (beginIndex < 0) {689 throw newStringIndexOutOfBoundsException(beginIndex);690 }691 if (endIndex >value.length) {692 throw newStringIndexOutOfBoundsException(endIndex);693 }694 int subLen = endIndex -beginIndex;695 if (subLen < 0) {696 throw newStringIndexOutOfBoundsException(subLen);697 }698 return ((beginIndex == 0) && (endIndex == value.length)) ? this

699 : newString(value, beginIndex, subLen);700 }701

702 public CharSequence subSequence(int beginIndex, intendIndex) {703 return this.substring(beginIndex, endIndex);704 }705

706 publicString concat(String str) {707 int otherLen =str.length();708 if (otherLen == 0) {709 return this;710 }711 int len =value.length;712 char buf[] = Arrays.copyOf(value, len +otherLen);713 str.getChars(buf, len);714 return new String(buf, true);715 }716

717 public String replace(char oldChar, charnewChar) {718 if (oldChar !=newChar) {719 int len =value.length;720 int i = -1;721 char[] val = value; /*avoid getfield opcode*/

722

723 while (++i

744 public booleanmatches(String regex) {745 return Pattern.matches(regex, this);746 }747

748 public booleancontains(CharSequence s) {749 return indexOf(s.toString()) > -1;750 }751

752 publicString replaceFirst(String regex, String replacement) {753 return Pattern.compile(regex).matcher(this).replaceFirst(replacement);754 }755

756 publicString replaceAll(String regex, String replacement) {757 return Pattern.compile(regex).matcher(this).replaceAll(replacement);758 }759

760 publicString replace(CharSequence target, CharSequence replacement) {761 returnPattern.compile(target.toString(), Pattern.LITERAL).matcher(762 this).replaceAll(Matcher.quoteReplacement(replacement.toString()));763 }764

765 public String[] split(String regex, intlimit) {766 /*fastpath if the regex is a767 (1)one-char String and this character is not one of the768 RegEx's meta characters ".$|()[{^?*+\\", or769 (2)two-char String and the first char is the backslash and770 the second is not the ascii digit or ascii letter.771 */

772 char ch = 0;773 if (((regex.value.length == 1 &&

774 ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||

775 (regex.length() == 2 &&

776 regex.charAt(0) == '\\' &&

777 (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&

778 ((ch-'a')|('z'-ch)) < 0 &&

779 ((ch-'A')|('Z'-ch)) < 0)) &&

780 (ch < Character.MIN_HIGH_SURROGATE ||

781 ch >Character.MAX_LOW_SURROGATE))782 {783 int off = 0;784 int next = 0;785 boolean limited = limit > 0;786 ArrayList list = new ArrayList<>();787 while ((next = indexOf(ch, off)) != -1) {788 if (!limited || list.size() < limit - 1) {789 list.add(substring(off, next));790 off = next + 1;791 } else { //last one792 //assert (list.size() == limit - 1);

793 list.add(substring(off, value.length));794 off =value.length;795 break;796 }797 }798 //If no match was found, return this

799 if (off == 0)800 return new String[]{this};801

802 //Add remaining segment

803 if (!limited || list.size()

806 //Construct result

807 int resultSize =list.size();808 if (limit == 0)809 while (resultSize > 0 && list.get(resultSize - 1).length() == 0)810 resultSize--;811 String[] result = newString[resultSize];812 return list.subList(0, resultSize).toArray(result);813 }814 return Pattern.compile(regex).split(this, limit);815 }816

817 publicString[] split(String regex) {818 return split(regex, 0);819 }820

821 publicString toLowerCase(Locale locale) {822 if (locale == null) {823 throw newNullPointerException();824 }825

826 intfirstUpper;827 final int len =value.length;828

829 /*Now check if there are any characters that need to be changed.*/

830 scan: {831 for (firstUpper = 0 ; firstUpper =Character.MIN_HIGH_SURROGATE)834 && (c <=Character.MAX_HIGH_SURROGATE)) {835 int supplChar =codePointAt(firstUpper);836 if (supplChar !=Character.toLowerCase(supplChar)) {837 breakscan;838 }839 firstUpper +=Character.charCount(supplChar);840 } else{841 if (c !=Character.toLowerCase(c)) {842 breakscan;843 }844 firstUpper++;845 }846 }847 return this;848 }849

850 char[] result = new char[len];851 int resultOffset = 0; /*result may grow, so i+resultOffset852 * is the write location in result*/

853

854 /*Just copy the first few lowerCase characters.*/

855 System.arraycopy(value, 0, result, 0, firstUpper);856

857 String lang =locale.getLanguage();858 boolean localeDependent =

859 (lang == "tr" || lang == "az" || lang == "lt");860 char[] lowerCharArray;861 intlowerChar;862 intsrcChar;863 intsrcCount;864 for (int i = firstUpper; i < len; i +=srcCount) {865 srcChar = (int)value[i];866 if ((char)srcChar >=Character.MIN_HIGH_SURROGATE867 && (char)srcChar <=Character.MAX_HIGH_SURROGATE) {868 srcChar =codePointAt(i);869 srcCount =Character.charCount(srcChar);870 } else{871 srcCount = 1;872 }873 if (localeDependent || srcChar == '\u03A3') { //GREEK CAPITAL LETTER SIGMA

874 lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);875 } else if (srcChar == '\u0130') { //LATIN CAPITAL LETTER I DOT

876 lowerChar =Character.ERROR;877 } else{878 lowerChar =Character.toLowerCase(srcChar);879 }880 if ((lowerChar ==Character.ERROR)881 || (lowerChar >=Character.MIN_SUPPLEMENTARY_CODE_POINT)) {882 if (lowerChar ==Character.ERROR) {883 if (!localeDependent && srcChar == '\u0130') {884 lowerCharArray =

885 ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH);886 } else{887 lowerCharArray =

888 ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);889 }890 } else if (srcCount == 2) {891 resultOffset += Character.toChars(lowerChar, result, i + resultOffset) -srcCount;892 continue;893 } else{894 lowerCharArray =Character.toChars(lowerChar);895 }896

897 /*Grow result if needed*/

898 int mapLen =lowerCharArray.length;899 if (mapLen >srcCount) {900 char[] result2 = new char[result.length + mapLen -srcCount];901 System.arraycopy(result, 0, result2, 0, i +resultOffset);902 result =result2;903 }904 for (int x = 0; x < mapLen; ++x) {905 result[i + resultOffset + x] =lowerCharArray[x];906 }907 resultOffset += (mapLen -srcCount);908 } else{909 result[i + resultOffset] = (char)lowerChar;910 }911 }912 return new String(result, 0, len +resultOffset);913 }914

915 publicString toLowerCase() {916 returntoLowerCase(Locale.getDefault());917 }918

919 publicString toUpperCase(Locale locale) {920 if (locale == null) {921 throw newNullPointerException();922 }923

924 intfirstLower;925 final int len =value.length;926

927 /*Now check if there are any characters that need to be changed.*/

928 scan: {929 for (firstLower = 0 ; firstLower =Character.MIN_HIGH_SURROGATE)933 && (c <=Character.MAX_HIGH_SURROGATE)) {934 c =codePointAt(firstLower);935 srcCount =Character.charCount(c);936 } else{937 srcCount = 1;938 }939 int upperCaseChar =Character.toUpperCaseEx(c);940 if ((upperCaseChar ==Character.ERROR)941 || (c !=upperCaseChar)) {942 breakscan;943 }944 firstLower +=srcCount;945 }946 return this;947 }948

949 char[] result = new char[len]; /*may grow*/

950 int resultOffset = 0; /*result may grow, so i+resultOffset951 * is the write location in result*/

952

953 /*Just copy the first few upperCase characters.*/

954 System.arraycopy(value, 0, result, 0, firstLower);955

956 String lang =locale.getLanguage();957 boolean localeDependent =

958 (lang == "tr" || lang == "az" || lang == "lt");959 char[] upperCharArray;960 intupperChar;961 intsrcChar;962 intsrcCount;963 for (int i = firstLower; i < len; i +=srcCount) {964 srcChar = (int)value[i];965 if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&

966 (char)srcChar <=Character.MAX_HIGH_SURROGATE) {967 srcChar =codePointAt(i);968 srcCount =Character.charCount(srcChar);969 } else{970 srcCount = 1;971 }972 if(localeDependent) {973 upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);974 } else{975 upperChar =Character.toUpperCaseEx(srcChar);976 }977 if ((upperChar ==Character.ERROR)978 || (upperChar >=Character.MIN_SUPPLEMENTARY_CODE_POINT)) {979 if (upperChar ==Character.ERROR) {980 if(localeDependent) {981 upperCharArray =

982 ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);983 } else{984 upperCharArray =Character.toUpperCaseCharArray(srcChar);985 }986 } else if (srcCount == 2) {987 resultOffset += Character.toChars(upperChar, result, i + resultOffset) -srcCount;988 continue;989 } else{990 upperCharArray =Character.toChars(upperChar);991 }992

993 /*Grow result if needed*/

994 int mapLen =upperCharArray.length;995 if (mapLen >srcCount) {996 char[] result2 = new char[result.length + mapLen -srcCount];997 System.arraycopy(result, 0, result2, 0, i +resultOffset);998 result =result2;999 }1000 for (int x = 0; x < mapLen; ++x) {1001 result[i + resultOffset + x] =upperCharArray[x];1002 }1003 resultOffset += (mapLen -srcCount);1004 } else{1005 result[i + resultOffset] = (char)upperChar;1006 }1007 }1008 return new String(result, 0, len +resultOffset);1009 }1010

1011 publicString toUpperCase() {1012 returntoUpperCase(Locale.getDefault());1013 }1014

1015 publicString trim() {1016 int len =value.length;1017 int st = 0;1018 char[] val = value; /*avoid getfield opcode*/

1019

1020 while ((st < len) && (val[st] <= ' ')) {1021 st++;1022 }1023 while ((st < len) && (val[len - 1] <= ' ')) {1024 len--;1025 }1026 return ((st > 0) || (len < value.length)) ? substring(st, len) : this;1027 }1028

1029 publicString toString() {1030 return this;1031 }1032

1033 public char[] toCharArray() {1034 //Cannot use Arrays.copyOf because of class initialization order issues

1035 char result[] = new char[value.length];1036 System.arraycopy(value, 0, result, 0, value.length);1037 returnresult;1038 }1039

1040 public staticString format(String format, Object... args) {1041 return newFormatter().format(format, args).toString();1042 }1043

1044 public staticString format(Locale l, String format, Object... args) {1045 return newFormatter(l).format(format, args).toString();1046 }1047

1048 public staticString valueOf(Object obj) {1049 return (obj == null) ? "null": obj.toString();1050 }1051

1052 public static String valueOf(chardata[]) {1053 return newString(data);1054 }1055

1056 public static String valueOf(char data[], int offset, intcount) {1057 return newString(data, offset, count);1058 }1059

1060 public static String copyValueOf(char data[], int offset, intcount) {1061 //All public String constructors now copy the data.

1062 return newString(data, offset, count);1063 }1064

1065 public static String copyValueOf(chardata[]) {1066 return newString(data);1067 }1068

1069 public static String valueOf(booleanb) {1070 return b ? "true" : "false";1071 }1072

1073 public static String valueOf(charc) {1074 char data[] ={c};1075 return new String(data, true);1076 }1077

1078 public static String valueOf(inti) {1079 returnInteger.toString(i);1080 }1081

1082 public static String valueOf(longl) {1083 returnLong.toString(l);1084 }1085

1086 public static String valueOf(floatf) {1087 returnFloat.toString(f);1088 }1089

1090 public static String valueOf(doubled) {1091 returnDouble.toString(d);1092 }1093

1094 public nativeString intern();1095

1096 private static final intHASHING_SEED;1097

1098 static{1099 long nanos =System.nanoTime();1100 long now =System.currentTimeMillis();1101 int SEED_MATERIAL[] ={1102 System.identityHashCode(String.class),1103 System.identityHashCode(System.class),1104 (int) (nanos >>> 32),1105 (int) nanos,1106 (int) (now >>> 32),1107 (int) now,1108 (int) (System.nanoTime() >>> 2)1109 };1110

1111 //Use murmur3 to scramble the seeding material.1112 //Inline implementation to avoid loading classes

1113 int h1 = 0;1114

1115 //body

1116 for (intk1 : SEED_MATERIAL) {1117 k1 *= 0xcc9e2d51;1118 k1 = (k1 << 15) | (k1 >>> 17);1119 k1 *= 0x1b873593;1120

1121 h1 ^=k1;1122 h1 = (h1 << 13) | (h1 >>> 19);1123 h1 = h1 * 5 + 0xe6546b64;1124 }1125

1126 //tail (always empty, as body is always 32-bit chunks)1127

1128 //finalization

1129

1130 h1 ^= SEED_MATERIAL.length * 4;1131

1132 //finalization mix force all bits of a hash block to avalanche

1133 h1 ^= h1 >>> 16;1134 h1 *= 0x85ebca6b;1135 h1 ^= h1 >>> 13;1136 h1 *= 0xc2b2ae35;1137 h1 ^= h1 >>> 16;1138

1139 HASHING_SEED =h1;1140 }1141

1142 private transient int hash32 = 0;1143

1144

1145 inthash32() {1146 int h =hash32;1147 if (0 ==h) {1148 //harmless data race on hash32 here.

1149 h = sun.misc.Hashing.murmur3_32(HASHING_SEED, value, 0, value.length);1150

1151 //ensure result is not zero to avoid recalcing

1152 h = (0 != h) ? h : 1;1153

1154 hash32 =h;1155 }1156

1157 returnh;1158 }1159 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值