JDK 8 String 源码详解(完整版带详细注释)
1. 基本结构和常量定义
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
// 序列化版本号
private static final long serialVersionUID = -6849794470754667710L;
// 用于存储字符串的字符数组
private final char value[];
// 字符串的哈希码缓存,延迟初始化
private int hash; // Default to 0
// 序列化相关常量
private static final ObjectStreamField[] serialPersistentFields =
new ObjectStreamField[0];
// 字符串比较器,忽略大小写
public static final Comparator<String> CASE_INSENSITIVE_ORDER
= new CaseInsensitiveComparator();
// 空字符串常量
public static final String EMPTY = "";
}
2. 构造函数
/**
* 无参构造函数
* 初始化一个空字符串
*/
public String() {
this.value = new char[0];
}
/**
* 从字符数组构造字符串
* @param value 字符数组
*/
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
/**
* 从字符数组的指定范围构造字符串
* @param value 字符数组
* @param offset 起始位置
* @param count 字符数量
* @throws IndexOutOfBoundsException 如果索引越界
*/
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count <= 0) {
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
if (offset <= value.length) {
this.value = new char[0];
return;
}
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.value = Arrays.copyOfRange(value, offset, offset+count);
}
/**
* 从Unicode码点数组构造字符串(Java 8新增)
* @param codePoints Unicode码点数组
* @param offset 起始位置
* @param count 码点数量
*/
public String(int[] codePoints, int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count <= 0) {
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
if (offset <= codePoints.length) {
this.value = new char[0];
return;
}
}
// Note: offset or count might be near -1>>>1.
if (offset > codePoints.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
final int end = offset + count;
// 计算需要的字符数组长度
int n = count;
for (int i = offset; i < end; i++) {
int c = codePoints[i];
if (Character.isBmpCodePoint(c))
continue;
else if (Character.isValidCodePoint(c))
n++;
else throw new IllegalArgumentException(Integer.toString(c));
}
final char[] v = new char[n];
// 转换码点到字符
for (int i = offset, j = 0; i < end; i++, j++) {
int c = codePoints[i];
if (Character.isBmpCodePoint(c))
v[j] = (char)c;
else
Character.toSurrogates(c, v, j++);
}
this.value = v;
}
/**
* 从字节数组构造字符串(使用平台默认字符集)
* @param bytes 字节数组
* @deprecated 使用指定字符集的构造函数
*/
@Deprecated
public String(byte bytes[]) {
this(bytes, 0, bytes.length);
}
/**
* 从字节数组的指定范围构造字符串(使用平台默认字符集)
* @param bytes 字节数组
* @param offset 起始位置
* @param length 字节数量
* @deprecated 使用指定字符集的构造函数
*/
@Deprecated
public String(byte bytes[], int offset, int length) {
checkBounds(bytes, offset, length);
this.value = StringCoding.decode(bytes, offset, length);
}
/**
* 从字节数组构造字符串(使用指定字符集)
* @param bytes 字节数组
* @param charsetName 字符集名称
* @throws UnsupportedEncodingException 如果字符集不支持
*/
public String(byte bytes[], String charsetName)
throws UnsupportedEncodingException {
this(bytes, 0, bytes.length, charsetName);
}
/**
* 从字节数组的指定范围构造字符串(使用指定字符集)
* @param bytes 字节数组
* @param offset 起始位置
* @param length 字节数量
* @param charsetName 字符集名称
* @throws UnsupportedEncodingException 如果字符集不支持
*/
public String(byte bytes[], int offset, int length, String charsetName)
throws UnsupportedEncodingException {
if (charsetName == null)
throw new NullPointerException("charsetName");
checkBounds(bytes, offset, length);
this.value = StringCoding.decode(charsetName, bytes, offset, length);
}
/**
* 从字节数组构造字符串(使用指定字符集)
* @param bytes 字节数组
* @param charset 字符集
*/
public String(byte bytes[], Charset charset) {
this(bytes, 0, bytes.length, charset);
}
/**
* 从字节数组的指定范围构造字符串(使用指定字符集)
* @param bytes 字节数组
* @param offset 起始位置
* @param length 字节数量
* @param charset 字符集
*/
public String(byte bytes[], int offset, int length, Charset charset) {
if (charset == null)
throw new NullPointerException("charset");
checkBounds(bytes, offset, length);
this.value = StringCoding.decode(charset, bytes, offset, length);
}
/**
* 从StringBuilder构造字符串
* @param builder StringBuilder对象
*/
public String(StringBuilder builder) {
this.value = Arrays.copyOf(builder.getValue(), builder.length());
}
/**
* 从StringBuffer构造字符串
* @param buffer StringBuffer对象
*/
public String(StringBuffer buffer) {
synchronized(buffer) {
this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
}
}
/**
* 包私有构造函数,用于优化性能
* @param value 字符数组
* @param share 无实际意义,用于区分构造函数
*/
String(char[] value, boolean share) {
// assert share : "unshared not supported";
this.value = value;
}
3. 核心方法实现
3.1 长度相关方法
/**
* 返回字符串的长度
* @return 字符串中字符的数量
*/
public int length() {
return value.length;
}
/**
* 判断字符串是否为空
* @return 如果字符串长度为0返回true
*/
public boolean isEmpty() {
return value.length == 0;
}
3.2 字符访问方法
/**
* 返回指定索引位置的字符
* @param index 字符索引
* @return 指定位置的字符
* @throws StringIndexOutOfBoundsException 如果索引越界
*/
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
/**
* 返回指定索引范围的字符序列
* @param start 起始索引(包含)
* @param end 结束索引(不包含)
* @return 指定范围的字符序列
* @throws StringIndexOutOfBoundsException 如果索引越界
*/
public CharSequence subSequence(int start, int end) {
return this.substring(start, end);
}
3.3 字符串比较方法
/**
* 比较两个字符串是否相等
* @param anObject 要比较的对象
* @return 如果相等返回true
*/
public boolean equals(Object anObject) {
// 如果是同一个对象,直接返回true
if (this == anObject) {
return true;
}
// 如果比较对象是String类型
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
// 长度不同直接返回false
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
// 逐个字符比较
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
/**
* 忽略大小写比较两个字符串
* @param anotherString 要比较的字符串
* @return 如果相等返回true
*/
public boolean equalsIgnoreCase(String anotherString) {
return (this == anotherString) ? true
: (anotherString != null)
&& (anotherString.value.length == value.length)
&& regionMatches(true, 0, anotherString, 0, value.length);
}
/**
* 比较两个字符串的字典顺序
* @param anotherString 要比较的字符串
* @return 比较结果:负数表示小于,0表示相等,正数表示大于
*/
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}
/**
* 忽略大小写比较两个字符串的字典顺序
* @param str 要比较的字符串
* @return 比较结果
*/
public int compareToIgnoreCase(String str) {
return CASE_INSENSITIVE_ORDER.compare(this, str);
}
/**
* 区域匹配
* @param ignoreCase 是否忽略大小写
* @param toffset 当前字符串的起始位置
* @param other 另一个字符串
* @param ooffset 另一个字符串的起始位置
* @param len 比较的字符数
* @return 如果匹配返回true
*/
public boolean regionMatches(boolean ignoreCase, int toffset,
String other, int ooffset, int len) {
char ta[] = value;
int to = toffset;
char pa[] = other.value;
int po = ooffset;
// 检查边界
if ((ooffset < 0) || (toffset < 0)
|| (toffset > (long)value.length - len)
|| (ooffset > (long)other.value.length - len)) {
return false;
}
while (len-- > 0) {
char c1 = ta[to++];
char c2 = pa[po++];
if (c1 == c2) {
continue;
}
if (ignoreCase) {
// 转换为大写比较
char u1 = Character.toUpperCase(c1);
char u2 = Character.toUpperCase(c2);
if (u1 == u2) {
continue;
}
if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
continue;
}
}
return false;
}
return true;
}
3.4 字符串查找方法
/**
* 判断字符串是否以指定前缀开始
* @param prefix 前缀
* @return 如果以指定前缀开始返回true
*/
public boolean startsWith(String prefix) {
return startsWith(prefix, 0);
}
/**
* 判断字符串从指定位置开始是否以指定前缀开始
* @param prefix 前缀
* @param toffset 起始位置
* @return 如果以指定前缀开始返回true
*/
public boolean startsWith(String prefix, int toffset) {
char ta[] = value;
int to = toffset;
char pa[] = prefix.value;
int po = 0;
int pc = prefix.value.length;
// 注意:在toffset处的隐式检查是否太接近value.length
if ((toffset < 0) || (toffset > value.length - pc)) {
return false;
}
while (--pc >= 0) {
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
}
/**
* 判断字符串是否以指定后缀结束
* @param suffix 后缀
* @return 如果以指定后缀结束返回true
*/
public boolean endsWith(String suffix) {
return startsWith(suffix, value.length - suffix.value.length);
}
/**
* 返回指定字符在字符串中第一次出现的索引
* @param ch 要查找的字符
* @return 第一次出现的索引,如果不存在返回-1
*/
public int indexOf(int ch) {
return indexOf(ch, 0);
}
/**
* 从指定位置开始查找指定字符在字符串中第一次出现的索引
* @param ch 要查找的字符
* @param fromIndex 起始位置
* @return 第一次出现的索引,如果不存在返回-1
*/
public int indexOf(int ch, int fromIndex) {
final int max = value.length;
if (fromIndex < 0) {
fromIndex = 0;
} else if (fromIndex >= max) {
// Note: fromIndex might be near -1>>>1.
return -1;
}
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// 处理基本多文种平面字符
final char[] value = this.value;
for (int i = fromIndex; i < max; i++) {
if (value[i] == ch) {
return i;
}
}
return -1;
} else {
// 处理补充字符
return indexOfSupplementary(ch, fromIndex);
}
}
/**
* 返回指定字符在字符串中最后一次出现的索引
* @param ch 要查找的字符
* @return 最后一次出现的索引,如果不存在返回-1
*/
public int lastIndexOf(int ch) {
return lastIndexOf(ch, value.length - 1);
}
/**
* 从指定位置开始向前查找指定字符在字符串中最后一次出现的索引
* @param ch 要查找的字符
* @param fromIndex 起始位置
* @return 最后一次出现的索引,如果不存在返回-1
*/
public int lastIndexOf(int ch, int fromIndex) {
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// 处理基本多文种平面字符
final char[] value = this.value;
int i = Math.min(fromIndex, value.length - 1);
for (; i >= 0; i--) {
if (value[i] == ch) {
return i;
}
}
return -1;
} else {
// 处理补充字符
return lastIndexOfSupplementary(ch, fromIndex);
}
}
/**
* 返回指定字符串在当前字符串中第一次出现的索引
* @param str 要查找的字符串
* @return 第一次出现的索引,如果不存在返回-1
*/
public int indexOf(String str) {
return indexOf(str, 0);
}
/**
* 从指定位置开始查找指定字符串在当前字符串中第一次出现的索引
* @param str 要查找的字符串
* @param fromIndex 起始位置
* @return 第一次出现的索引,如果不存在返回-1
*/
public int indexOf(String str, int fromIndex) {
return indexOf(value, 0, value.length,
str.value, 0, str.value.length, fromIndex);
}
/**
* 字符串查找的核心实现
*/
static int indexOf(char[] source, int sourceOffset, int sourceCount,
char[] target, int targetOffset, int targetCount,
int fromIndex) {
if (fromIndex >= sourceCount) {
return (targetCount == 0 ? sourceCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}
char first = target[targetOffset];
int max = sourceOffset + (sourceCount - targetCount);
for (int i = sourceOffset + fromIndex; i <= max; i++) {
// 查找第一个字符
if (source[i] != first) {
while (++i <= max && source[i] != first);
}
// 找到第一个字符后,继续匹配剩余字符
if (i <= max) {
int j = i + 1;
int end = j + targetCount - 1;
for (int k = targetOffset + 1; j < end && source[j]
== target[k]; j++, k++);
if (j == end) {
// 找到完全匹配
return i - sourceOffset;
}
}
}
return -1;
}
3.5 字符串提取方法
/**
* 返回字符串的子字符串
* @param beginIndex 起始索引(包含)
* @return 子字符串
* @throws StringIndexOutOfBoundsException 如果索引越界
*/
public String substring(int beginIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
int subLen = value.length - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}
/**
* 返回字符串的子字符串
* @param beginIndex 起始索引(包含)
* @param endIndex 结束索引(不包含)
* @return 子字符串
* @throws StringIndexOutOfBoundsException 如果索引越界
*/
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
3.6 字符串转换方法
/**
* 将字符串转换为字符数组
* @return 字符数组
*/
public char[] toCharArray() {
// 不能直接返回内部数组,需要复制
return Arrays.copyOf(value, value.length);
}
/**
* 将字符串转换为小写
* @param locale 本地化信息
* @return 小写字符串
*/
public String toLowerCase(Locale locale) {
if (locale == null) {
throw new NullPointerException();
}
int firstUpper;
final int len = value.length;
// 快速检查:如果字符串已经是小写,直接返回
scan: {
for (firstUpper = 0 ; firstUpper < len; ) {
char c = value[firstUpper];
if ((c >= Character.MIN_HIGH_SURROGATE) &&
(c <= Character.MAX_HIGH_SURROGATE)) {
int supplChar = codePointAt(firstUpper);
if (supplChar != Character.toLowerCase(supplChar)) {
break scan;
}
firstUpper += Character.charCount(supplChar);
} else {
if (c != Character.toLowerCase(c)) {
break scan;
}
firstUpper++;
}
}
return this;
}
char[] result = new char[len];
int resultOffset = 0; // result数组中的位置
System.arraycopy(value, 0, result, 0, firstUpper);
String lang = locale.getLanguage();
boolean localeDependent =
(lang == "tr" || lang == "az" || lang == "lt");
char[] lowerCharArray;
int lowerChar;
int srcChar;
int srcCount;
for (int i = firstUpper; i < len; i += srcCount) {
srcChar = (int)value[i];
if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
(char)srcChar <= Character.MAX_HIGH_SURROGATE) {
srcChar = codePointAt(i);
}
if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA
lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
} else if (srcChar == '\u0307' && i > 0 && value[i-1] == '\u0069') {
// Special case of 0307 (combining dot above)
// preceded by 0069 (latin small letter i)
lowerChar = 0;
} else {
lowerChar = Character.toLowerCase(srcChar);
}
if ((Character.isSupplementaryCodePoint(lowerChar)) ||
(lowerChar == Character.ERROR)) {
if (lowerChar == Character.ERROR) {
lowerCharArray =
ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
} else if (srcChar == '\u03A3') {
lowerCharArray = GreekLetters.toLowerCaseCharArray(this, i);
} else {
lowerCharArray = Character.toChars(lowerChar);
}
System.arraycopy(result, 0, result, 0, resultOffset);
char[] result2 = new char[result.length + lowerCharArray.length - 1];
System.arraycopy(result, 0, result2, 0, resultOffset);
result = result2;
for (int j = 0; j < lowerCharArray.length; j++) {
result[resultOffset++] = lowerCharArray[j];
}
} else {
result[resultOffset++] = (char)lowerChar;
}
srcCount = 1;
if (srcChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT) {
srcCount = Character.charCount(srcChar);
}
}
return new String(result, 0, resultOffset);
}
/**
* 将字符串转换为小写(使用默认本地化)
* @return 小写字符串
*/
public String toLowerCase() {
return toLowerCase(Locale.getDefault());
}
/**
* 将字符串转换为大写
* @param locale 本地化信息
* @return 大写字符串
*/
public String toUpperCase(Locale locale) {
if (locale == null) {
throw new NullPointerException();
}
int firstLower;
final int len = value.length;
// 快速检查:如果字符串已经是大写,直接返回
scan: {
for (firstLower = 0 ; firstLower < len; ) {
int c = (int)value[firstLower];
int srcCount;
if ((c >= Character.MIN_HIGH_SURROGATE) &&
(c <= Character.MAX_HIGH_SURROGATE)) {
c = codePointAt(firstLower);
srcCount = Character.charCount(c);
} else {
srcCount = 1;
}
int upperCaseChar = Character.toUpperCaseEx(c);
if ((upperCaseChar == Character.ERROR) ||
(c != upperCaseChar)) {
break scan;
}
firstLower += srcCount;
}
return this;
}
// 结果可能比原始字符串长,所以需要动态调整
char[] result = new char[len * 3 / 2];
int resultOffset = 0;
System.arraycopy(value, 0, result, 0, firstLower);
String lang = locale.getLanguage();
boolean localeDependent =
(lang == "tr" || lang == "az" || lang == "lt");
char[] upperCharArray;
int upperChar;
int srcChar;
int srcCount;
for (int i = firstLower; i < len; i += srcCount) {
srcChar = (int)value[i];
if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
(char)srcChar <= Character.MAX_HIGH_SURROGATE) {
srcChar = codePointAt(i);
}
if (localeDependent) {
upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
} else {
upperChar = Character.toUpperCaseEx(srcChar);
}
if ((Character.isSupplementaryCodePoint(upperChar)) ||
(upperChar == Character.ERROR)) {
if (upperChar == Character.ERROR) {
if (localeDependent) {
upperCharArray =
ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
} else {
upperCharArray = Character.toUpperCaseCharArray(srcChar);
}
} else {
upperCharArray = Character.toChars(upperChar);
}
int mapLen = upperCharArray.length;
if (mapLen > 1) {
char[] result2 = new char[result.length + mapLen - 1];
System.arraycopy(result, 0, result2, 0, resultOffset);
result = result2;
}
for (int x = 0; x < mapLen; ++x) {
result[resultOffset++] = upperCharArray[x];
}
} else {
result[resultOffset++] = (char)upperChar;
}
srcCount = 1;
if (srcChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT) {
srcCount = Character.charCount(srcChar);
}
}
return new String(result, 0, resultOffset);
}
/**
* 将字符串转换为大写(使用默认本地化)
* @return 大写字符串
*/
public String toUpperCase() {
return toUpperCase(Locale.getDefault());
}
3.7 字符串修剪和替换方法
/**
* 去除字符串首尾的空白字符
* @return 修剪后的字符串
*/
public String trim() {
int len = value.length;
int st = 0;
char[] val = value; // avoid getfield opcode
// 找到第一个非空白字符
while ((st < len) && (val[st] <= ' ')) {
st++;
}
// 找到最后一个非空白字符
while ((st < len) && (val[len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}
/**
* 替换字符串中所有指定字符
* @param oldChar 要被替换的字符
* @param newChar 替换的字符
* @return 替换后的字符串
*/
public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
int len = value.length;
int i = -1;
char[] val = value; // avoid getfield opcode
// 查找第一个需要替换的字符
while (++i < len) {
if (val[i] == oldChar) {
break;
}
}
if (i < len) {
char buf[] = new char[len];
for (int j = 0; j < i; j++) {
buf[j] = val[j];
}
while (i < len) {
char c = val[i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(buf, true);
}
}
return this;
}
/**
* 判断字符串是否匹配给定的正则表达式
* @param regex 正则表达式
* @return 如果匹配返回true
*/
public boolean matches(String regex) {
return Pattern.matches(regex, this);
}
/**
* 替换第一个匹配给定正则表达式的子字符串
* @param regex 正则表达式
* @param replacement 替换字符串
* @return 替换后的字符串
*/
public String replaceFirst(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
}
/**
* 替换所有匹配给定正则表达式的子字符串
* @param regex 正则表达式
* @param replacement 替换字符串
* @return 替换后的字符串
*/
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
/**
* 替换目标字符串为指定字符串
* @param target 要被替换的字符串
* @param replacement 替换字符串
* @return 替换后的字符串
*/
public String replace(CharSequence target, CharSequence replacement) {
String tgtStr = target.toString();
String replStr = replacement.toString();
int j = indexOf(tgtStr);
if (j < 0) {
return this;
}
int tgtLen = tgtStr.length();
int tgtLen1 = (tgtLen > 0) ? tgtLen : 1;
int thisLen = length();
int newLenHint = thisLen - tgtLen + replStr.length();
if (newLenHint < 0) {
throw new OutOfMemoryError();
}
StringBuilder sb = new StringBuilder(newLenHint);
int i = 0;
do {
sb.append(this, i, j);
sb.append(replStr);
i = j + tgtLen;
} while (j < thisLen && (j = indexOf(tgtStr, j + tgtLen1)) > 0);
sb.append(this, i, thisLen);
return sb.toString();
}
3.8 字符串分割方法
/**
* 根据正则表达式分割字符串
* @param regex 正则表达式
* @return 分割后的字符串数组
*/
public String[] split(String regex) {
return split(regex, 0);
}
/**
* 根据正则表达式分割字符串
* @param regex 正则表达式
* @param limit 限制分割的数量
* @return 分割后的字符串数组
*/
public String[] split(String regex, int limit) {
// 快速路径:如果分隔符是单个字符且不是正则表达式特殊字符
char ch = 0;
if (((regex.value.length == 1 &&
".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
(regex.length() == 2 &&
regex.charAt(0) == '\\' &&
(((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
((ch-'a')|('z'-ch)) < 0 &&
((ch-'A')|('Z'-ch)) < 0)) &&
(ch < Character.MIN_HIGH_SURROGATE ||
ch > Character.MAX_LOW_SURROGATE))
{
int off = 0;
int next = 0;
boolean limited = limit > 0;
ArrayList<String> list = new ArrayList<>();
while ((next = indexOf(ch, off)) != -1) {
if (!limited || list.size() < limit - 1) {
list.add(substring(off, next));
off = next + 1;
} else { // last one
list.add(substring(off, value.length));
off = value.length;
break;
}
}
// If no match was found, return this
if (off == 0)
return new String[]{this};
// Add remaining segment
if (!limited || list.size() < limit)
list.add(substring(off, value.length));
// Construct result
int resultSize = list.size();
if (limit == 0) {
while (resultSize > 0 && list.get(resultSize - 1).length() == 0) {
resultSize--;
}
}
String[] result = new String[resultSize];
return list.subList(0, resultSize).toArray(result);
}
return Pattern.compile(regex).split(this, limit);
}
4. 哈希码和字符串连接
4.1 哈希码计算
/**
* 计算字符串的哈希码
* @return 哈希码
*/
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
// 使用经典的哈希算法:s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
4.2 字符串连接
/**
* 连接两个字符串
* @param str 要连接的字符串
* @return 连接后的字符串
*/
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}
/**
* 将指定字符复制到字符数组中
* @param dst 目标字符数组
* @param dstBegin 目标数组的起始位置
*/
void getChars(char dst[], int dstBegin) {
System.arraycopy(value, 0, dst, dstBegin, value.length);
}
5. 其他重要方法
5.1 字符序列方法
/**
* 返回指定索引处的字符代码点
* @param index 索引
* @return 代码点
*/
public int codePointAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return Character.codePointAtImpl(value, index, value.length);
}
/**
* 返回指定索引之前的字符代码点
* @param index 索引
* @return 代码点
*/
public int codePointBefore(int index) {
int i = index - 1;
if ((i < 0) || (i >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return Character.codePointBeforeImpl(value, index, 0);
}
/**
* 返回指定范围内的代码点数量
* @param beginIndex 起始索引
* @param endIndex 结束索引
* @return 代码点数量
*/
public int codePointCount(int beginIndex, int endIndex) {
if (beginIndex < 0 || endIndex > value.length || beginIndex > endIndex) {
throw new IndexOutOfBoundsException();
}
return Character.codePointCountImpl(value, beginIndex, endIndex - beginIndex);
}
5.2 格式化方法
/**
* 返回格式化的字符串
* @param format 格式字符串
* @param args 参数
* @return 格式化后的字符串
*/
public static String format(String format, Object... args) {
return new Formatter().format(format, args).toString();
}
/**
* 返回格式化的字符串(指定本地化)
* @param l 本地化信息
* @param format 格式字符串
* @param args 参数
* @return 格式化后的字符串
*/
public static String format(Locale l, String format, Object... args) {
return new Formatter(l).format(format, args).toString();
}
5.3 转换为其他类型
/**
* 将字符串转换为字节数组(使用平台默认字符集)
* @return 字节数组
* @deprecated 使用指定字符集的方法
*/
@Deprecated
public byte[] getBytes() {
return StringCoding.encode(value, 0, value.length);
}
/**
* 将字符串转换为字节数组(使用指定字符集)
* @param charsetName 字符集名称
* @return 字节数组
* @throws UnsupportedEncodingException 如果字符集不支持
*/
public byte[] getBytes(String charsetName)
throws UnsupportedEncodingException {
if (charsetName == null) throw new NullPointerException();
return StringCoding.encode(charsetName, value, 0, value.length);
}
/**
* 将字符串转换为字节数组(使用指定字符集)
* @param charset 字符集
* @return 字节数组
*/
public byte[] getBytes(Charset charset) {
if (charset == null) throw new NullPointerException();
return StringCoding.encode(charset, value, 0, value.length);
}
6. 静态工具方法
6.1 字符串复制
/**
* 复制指定的字符串
* @param str 要复制的字符串
* @return 复制的字符串
*/
public static String copyValueOf(char data[]) {
return new String(data);
}
/**
* 复制字符数组的指定范围
* @param data 字符数组
* @param offset 起始位置
* @param count 字符数量
* @return 复制的字符串
*/
public static String copyValueOf(char data[], int offset, int count) {
return new String(data, offset, count);
}
/**
* 返回指定字符数组表示的字符串
* @param data 字符数组
* @return 字符串
*/
public static String valueOf(char data[]) {
return new String(data);
}
/**
* 返回指定字符数组指定范围表示的字符串
* @param data 字符数组
* @param offset 起始位置
* @param count 字符数量
* @return 字符串
*/
public static String valueOf(char data[], int offset, int count) {
return new String(data, offset, count);
}
6.2 基本类型转换
/**
* 返回boolean值的字符串表示
* @param b boolean值
* @return 字符串表示
*/
public static String valueOf(boolean b) {
return b ? "true" : "false";
}
/**
* 返回char值的字符串表示
* @param c char值
* @return 字符串表示
*/
public static String valueOf(char c) {
char data[] = {c};
return new String(data, true);
}
/**
* 返回int值的字符串表示
* @param i int值
* @return 字符串表示
*/
public static String valueOf(int i) {
return Integer.toString(i);
}
/**
* 返回long值的字符串表示
* @param l long值
* @return 字符串表示
*/
public static String valueOf(long l) {
return Long.toString(l);
}
/**
* 返回float值的字符串表示
* @param f float值
* @return 字符串表示
*/
public static String valueOf(float f) {
return Float.toString(f);
}
/**
* 返回double值的字符串表示
* @param d double值
* @return 字符串表示
*/
public static String valueOf(double d) {
return Double.toString(d);
}
/**
* 返回对象的字符串表示
* @param obj 对象
* @return 字符串表示
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
7. 内部辅助方法
/**
* 检查字节数组边界
*/
private static void checkBounds(byte[] bytes, int offset, int length) {
if (length < 0)
throw new StringIndexOutOfBoundsException(length);
if (offset < 0)
throw new StringIndexOutOfBoundsException(offset);
if (offset > bytes.length - length)
throw new StringIndexOutOfBoundsException(offset + length);
}
/**
* 处理补充字符的indexOf
*/
private int indexOfSupplementary(int ch, int fromIndex) {
if (Character.isValidCodePoint(ch)) {
final char[] value = this.value;
final char hi = Character.highSurrogate(ch);
final char lo = Character.lowSurrogate(ch);
final int max = value.length - 1;
for (int i = fromIndex; i < max; i++) {
if (value[i] == hi && value[i + 1] == lo) {
return i;
}
}
}
return -1;
}
/**
* 处理补充字符的lastIndexOf
*/
private int lastIndexOfSupplementary(int ch, int fromIndex) {
if (Character.isValidCodePoint(ch)) {
final char[] value = this.value;
char hi = Character.highSurrogate(ch);
char lo = Character.lowSurrogate(ch);
int i = Math.min(fromIndex, value.length - 2);
for (; i >= 0; i--) {
if (value[i] == hi && value[i + 1] == lo) {
return i;
}
}
}
return -1;
}
8. 总结
8.1 String类的特点
- 不可变性:String对象一旦创建就不能修改,所有修改操作都会创建新的String对象
- 线程安全:由于不可变性,String是线程安全的
- 字符串池:相同的字符串字面量会共享同一个对象
- 字符存储:使用char数组存储字符数据
- UTF-16编码:内部使用UTF-16编码存储Unicode字符
8.2 性能优化
- 字符串池:通过字符串池减少内存使用
- 哈希码缓存:缓存哈希码避免重复计算
- 字符数组复用:在某些情况下复用字符数组
- 快速路径优化:针对常见情况的优化
8.3 时间复杂度分析
- 访问字符:O(1) - 直接数组访问
- 字符串比较:O(n) - 需要逐个字符比较
- 字符串查找:O(n*m) - 最坏情况,n为字符串长度,m为查找字符串长度
- 字符串连接:O(n+m) - 需要创建新数组并复制字符
- 哈希码计算:O(n) - 需要遍历所有字符
8.4 使用建议
-
字符串连接:
- 少量字符串连接使用+操作符
- 大量字符串连接使用StringBuilder
-
字符串比较:
- 使用equals()方法比较字符串内容
- 使用==比较字符串引用
-
字符串查找:
- 使用indexOf()系列方法
- 复杂查找使用正则表达式
-
内存优化:
- 避免创建不必要的字符串对象
- 及时释放不需要的字符串引用
8.5 与其他字符串类的比较
特性 | String | StringBuilder | StringBuffer |
---|---|---|---|
可变性 | 不可变 | 可变 | 可变 |
线程安全 | 是 | 否 | 是 |
性能 | 中等 | 高 | 低 |
适用场景 | 不变字符串 | 单线程字符串操作 | 多线程字符串操作 |
String类是Java中最基础和最重要的类之一,理解其内部实现对于编写高效的Java程序至关重要。其不可变性和字符串池机制是Java语言设计的精华所在。