首先看String类导入的包名称与类修饰符号
package java.lang; //说明是属于java.lang包路径下面的类
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence //String是被final修饰的类,所以不能被继承,同时实现了Serializable接口,可以序列化
看下String中常用的方法:
equals方法
public boolean equals(Object anObject) {
//首先用==符号来判断这两个是否相等,如果相等就返回true
if (this == anObject) {
return true;
}
//首先判断这两个String对象长度是否相等,如果长度相等,再化成一个char类型数组,然后将每个对应的元素相比较,如果有一个不等于就返回false
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
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;
}
equalsIgnoreCase方法:
public boolean equalsIgnoreCase(String anotherString) {
//在这里全部都是用==,以及长度的比较,最后同时也调用了regionMatches方法
return (this == anotherString) ? true
: (anotherString != null)
&& (anotherString.value.length == value.length)
&& regionMatches(true, 0, anotherString, 0, value.length);
}
//对regionMatches方法
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) {
// 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
// 再次进行校验
if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
continue;
}
}
return false;
}
return true;
}
replace方法:
public String replace(char oldChar, char newChar) {
//首先判断两个char对象是否相等
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;
}