2.1String类
想要了解一个类,最好的办法就是看这个类的实现源代码:
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence
{
/** 该值用于字符存储 */
private final char value[];
/** 偏移量是所使用存储的第一个索引。 */
private final int offset;
/** 计数是字符串中的字符数。 */
private final int count;
/** 缓存字符串的哈希码 */
private int hash; // 默认为0
/** 使用JDK 1.0.2中的serialVersionUID实现互操作性 */
private static final long serialVersionUID = -6849794470754667710L;
........
}
从上面可以看出几点:
1)**String类时final类,也即以为着String类不能被继承,并且它的成员方法都默认为final方法。**在Java中该类中的成员方法都默认为fianl方法。
2)上面列举出了String类中所有的成员属性,从上面可以看出String类其实是通过char数组来保存字符串的。
String类一些方法实现:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
char buf[] = new char[count + otherLen];
getChars(0, count, buf, 0);
str.getChars(0, otherLen, buf, count);
return new String(0, count + otherLen, buf);
}
public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
int len = count;
int i = -1;
char[] val = value; /* 避免getfield操作码 */
int off = offset; /* 避免getfield操作码 */
while (++i < len) {
if (val[off + i] == oldChar) {
break;
}
}
if (i < len) {
char buf[] = new char[len];
for (int j = 0 ; j < i ; j++) {
buf[j] = val[off+j];
}
while (i < len) {
char c = val[off + i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(0, len, buf);
}
}
return this;
}
从上面的三个方法可以看出,无论是substing、concat还是replace操作都不是在原有的字符串上进行的,而是重新生成一个新的字符串对象。也就是说进行这些操作后,最开始的字符串并没有被改变。
在这里要永远记住一点:“String对象以但被创建就是固定不变了,对String对象的任何改变都不影响到原对象,相关的任何change操作都会生成新的对象”。
github: github.com/ccy524946/t…