String类代表字符串
位置:java.lang.String
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length); // 按照数组的长度,复制数组到value
}
public String(char value[], int offset, int count) {
if (offset < 0) { //判断偏置是否小于0,小于0抛异常
throw new StringIndexOutOfBoundsException(offset);
}
if (count <= 0) { //判断截取的字符数
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
if (offset <= value.length) {
this.value = "".value; // 直接返回空字符串
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); // 复制截取的部分,范围复制
}
public String(StringBuffer buffer) {//线程安全,可变的字符序列.字符串缓冲区就像一个String ,但可以修改
synchronized(buffer) { // 同步机制
this.value = Arrays.copyOf(buffer.getValue(), buffer.length()); // 将buffer中的字符串数据复制到value中
}
}
public String(StringBuilder builder) {//StringBuilder和StringBuffer类似,但不保证同步
this.value = Arrays.copyOf(builder.getValue(), builder.length());
}
字段名 | 说明 |
---|---|
value | 存储字符 |
hash | 存储hashCode |
serialVersionUID | 序列号 |
CASE_INSENSITIVE_ORDER | 一个比较器 |
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) { //索引值小于零或者大于字符串长度
throw new StringIndexOutOfBoundsException(index); //"String index out of range: " + index
}
return value[index]; //value是字符数组,String中的值是通过数组存储的
}
public boolean equals(Object anObject) {
if (this == anObject) { //比较内存地址(引用类型),而基本数据类型是比较值
return true;
}
if (anObject instanceof String) {//如果anObject是String类型
String anotherString = (String)anObject;//强制转换
int n = value.length; //this字符串的长度
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;
}
public String substring(int beginIndex) {
if (beginIndex < 0) { //索引小于0
throw new StringIndexOutOfBoundsException(beginIndex); //"String index out of range: " + index
}
int subLen = value.length - beginIndex; //子串的长度
if (subLen < 0) { //索引超过数据长度
throw new StringIndexOutOfBoundsException(subLen);
}
return (beginIndex == 0) ? this : new String(value, beginIndex, subLen); //直接根据构造函数new一个子串
}
public boolean regionMatches(int toffset, String other, int ooffset,
int len) {
char ta[] = value;
int to = toffset; //当前字符串的开始索引
char pa[] = other.value;
int po = ooffset; //要比较的字符串的开始索引
// Note: toffset, ooffset, or len might be near -1>>>1.
if ((ooffset < 0) || (toffset < 0)
|| (toffset > (long)value.length - len)
|| (ooffset > (long)other.value.length - len)) { //索引设置错误
return false;
}
while (len-- > 0) {
if (ta[to++] != pa[po++]) { // 子串之间逐位比较
return false;
}
}
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;
// Note: toffset, ooffset, or len might be near -1>>>1.
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) { //忽略大小写,比较方法就是将要比较的字母都转换成大写或小写
// If characters don't match but case may be ignored,
// try converting both characters to uppercase.
// If the results match, then the comparison scan should
// continue.
char u1 = Character.toUpperCase(c1);
char u2 = Character.toUpperCase(c2);
if (u1 == u2) {
continue;
}
// Unfortunately, conversion to uppercase does not work properly
// for the Georgian alphabet, which has strange rules about case
// conversion. So we need to make one last check before
// exiting. 特例:格鲁吉亚字母对大写不敏感,所以要全部转换成小写
if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
continue;
}
}
return false;
}
return true;
}
public int indexOf(int ch, int fromIndex) { // 返回某个字母在字符串中第一次出现的索引
final int max = value.length; // 不可修改
if (fromIndex < 0) { // 开始索引为负数则直接置为0
fromIndex = 0;
} else if (fromIndex >= max) { //索引超过字符串长度,直接返回-1
// Note: fromIndex might be near -1>>>1.
return -1;
}
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// handle most cases here (ch is a BMP code point or a
// negative value (invalid code point))
final char[] value = this.value;
for (int i = fromIndex; i < max; i++) {
if (value[i] == ch) { //比较
return i;
}
}
return -1; //没有对应字母,返回-1
} else { //是补充字母
return indexOfSupplementary(ch, fromIndex);
}
}
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;
// Note: toffset might be near -1>>>1.
if ((toffset < 0) || (toffset > value.length - pc)) {
return false; //索引小于0或者字符串减去前缀的长度
}
while (--pc >= 0) {
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
}
public boolean endsWith(String suffix) {
return startsWith(suffix, value.length - suffix.value.length);
}
判断这个常量是否存在于常量池。
如果存在
判断存在内容是引用还是常量,
如果是引用,
返回引用地址指向堆空间对象,
如果是常量,
直接返回常量池常量
如果不存在,
将当前对象引用复制到常量池,并且返回的是当前对象的引用
参考博文: https://blog.csdn.net/u013366617/article/details/83618361
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i]; //注意int类型数据的越界问题
}
hash = h;
}
return h;
}
public String trim() { //删除所有前导空格和尾随空格
int len = value.length;
int st = 0; //首位
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[st] <= ' ')) { //空格的ASCII码是32,是有效字符中最小的一个
st++;
}
while ((st < len) && (val[len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}
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]; // 将之前的字符数组拷贝到buf数组
}
while (i < len) { // 逐个字母开始判断
char c = val[i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(buf, true);
}
}
return this; // 没有字符需要替换,直接返回this字符串
}
public String[] split(String regex, int limit) {
char ch = 0;
// if判断的条件有3中:
// 1、如果 匹配规则regex长度为1 且 不是 ".$|()[{^?*+\\" 中的特殊字符
// 2、 匹配规则regex长度为2 且 第一个字符为转义字符\,第二个字符不是字母或数字
// 3、 编码
// 并给 ch 赋值
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))
{
// off和next 分别表示 截取子串时的上下索引,初始都为0
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) {
// 当 off=next时 截取的是空串
list.add(substring(off, next));
// 子串截完以后 下次截取的初始索引从next的下一位开始
off = next + 1;
} else { // last one
list.add(substring(off, value.length));
off = value.length;
break;
}
}
if (off == 0)
return new String[]{this};
if (!limited || list.size() < limit)
list.add(substring(off, value.length));
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);
}
public char[] toCharArray() {
// Cannot use Arrays.copyOf because of class initialization order issues
char result[] = new char[value.length];
System.arraycopy(value, 0, result, 0, value.length); //本地方法
return result;
}
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) { // 比较lim内个字符
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) { //第一个字符不相等的Unicode值
return c1 - c2;
}
k++;
}
return len1 - len2; //都相等(两字符串一致),返回0
}
public boolean contentEquals(CharSequence cs) { //CharSequence有三个接口实现的类,需要分开处理
// Argument is a StringBuffer, StringBuilder
if (cs instanceof AbstractStringBuilder) { //判断类型
if (cs instanceof StringBuffer) { //StringBuffer
synchronized(cs) { //同步方法,加锁,StringBuffer是线程安全的,需要处理并发场景
return nonSyncContentEquals((AbstractStringBuilder)cs);
}
} else { //StringBuilder是单线程的
return nonSyncContentEquals((AbstractStringBuilder)cs);
}
}
// Argument is a String
if (cs instanceof String) {
return equals(cs); //String的equals方法
}
// Argument is a generic CharSequence
char v1[] = value;
int n = v1.length;
if (n != cs.length()) {
return false;
}
for (int i = 0; i < n; i++) {
if (v1[i] != cs.charAt(i)) {
return false;
}
}
return true;
}
private boolean nonSyncContentEquals(AbstractStringBuilder sb) {
char v1[] = value;
char v2[] = sb.getValue();
int n = v1.length;
if (n != sb.length()) {
return false;
}
for (int i = 0; i < n; i++) {
if (v1[i] != v2[i]) {
return false;
}
}
return true;
}
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); //将str复制到数组中,位置从value.length后开始
return new String(buf, true); // 返回参数是char数组的String 构造函数
}
public String toLowerCase(Locale locale) {
if (locale == null) { // 没有地区,程序无法执行,故抛出空指针异常
throw new NullPointerException();
}
int firstUpper;
final int len = value.length;
/* Now check if there are any characters that need to be changed. */
scan: { // 这是带标签的break语句
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 may grow, so i+resultOffset
* is the write location in result */
/* Just copy the first few lowerCase characters. */
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);
srcCount = Character.charCount(srcChar);
} else {
srcCount = 1;
}
if (localeDependent ||
srcChar == '\u03A3' || // GREEK CAPITAL LETTER SIGMA
srcChar == '\u0130') { // LATIN CAPITAL LETTER I WITH DOT ABOVE
lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
} else {
lowerChar = Character.toLowerCase(srcChar);
}
if ((lowerChar == Character.ERROR)
|| (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
if (lowerChar == Character.ERROR) {
lowerCharArray =
ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
} else if (srcCount == 2) {
resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
continue;
} else {
lowerCharArray = Character.toChars(lowerChar);
}
/* Grow result if needed */
int mapLen = lowerCharArray.length;
if (mapLen > srcCount) {
char[] result2 = new char[result.length + mapLen - srcCount];
System.arraycopy(result, 0, result2, 0, i + resultOffset);
result = result2;
}
for (int x = 0; x < mapLen; ++x) {
result[i + resultOffset + x] = lowerCharArray[x];
}
resultOffset += (mapLen - srcCount);
} else {
result[i + resultOffset] = (char)lowerChar;
}
}
return new String(result, 0, len + resultOffset);
}
public int compareToIgnoreCase(String str) {
return CASE_INSENSITIVE_ORDER.compare(this, str);
}
public static final Comparator<String> CASE_INSENSITIVE_ORDER = new CaseInsensitiveComparator(); //忽略大小写比较器
private static class CaseInsensitiveComparator
implements Comparator<String>, java.io.Serializable {
// use serialVersionUID from JDK 1.2.2 for interoperability
private static final long serialVersionUID = 8575799808933029326L;
public int compare(String s1, String s2) {
int n1 = s1.length();
int n2 = s2.length();
int min = Math.min(n1, n2);
for (int i = 0; i < min; i++) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 != c2) {
c1 = Character.toUpperCase(c1);
c2 = Character.toUpperCase(c2);
if (c1 != c2) {
c1 = Character.toLowerCase(c1);
c2 = Character.toLowerCase(c2);
if (c1 != c2) {
// No overflow because of numeric promotion
return c1 - c2;
}
}
}
}
return n1 - n2;
}
/** Replaces the de-serialized object. */
private Object readResolve() { return CASE_INSENSITIVE_ORDER; }
}
public static String valueOf(char c) {
char data[] = {c};//转成char数组
return new String(data, true);//调用构造函数
}
String message = String.join("-", "Java", "is", "cool"); // message returned is: "Java-is-cool"
public static String join(CharSequence delimiter, CharSequence... elements) { // elments用delimiter进行组合,返回一个字符串
Objects.requireNonNull(delimiter); //判断非空
Objects.requireNonNull(elements);
// Number of elements not likely worth Arrays.stream overhead.
StringJoiner joiner = new StringJoiner(delimiter); //字符串构造器,分隔符由delimiter指定
for (CharSequence cs: elements) {
joiner.add(cs); //逐个添加,分隔符在add方法中已经添加
}
return joiner.toString(); // 转换为String对象
}