了解类的最好方法是查看它的实现源代码
jdk1.6.0_14 SRC Java lang string.Java
如果你打开类文件,你会看到String类是final:
public final class String
implements java.io.Serializable, Comparable, CharSequence
{
private final char value[];
private final int offset;
private final int count;
private int hash; // Default to 0
private static final long serialVersionUID = -6849794470754667710L;
......
}
从上面可以看出几点:
1) String类是final类,这意味着String类不能被继承,默认情况下它的成员方法都是final。在Java中,不允许继承带有final修饰的类,该类中的所有成员方法默认为final方法。在早期的JVM实现中,final修改的方法被转换为内联调用,以提高执行效率。从Java SE5/6开始,这种方法就逐渐被抛弃了。因此,在当前版本的Java SE中,不需要考虑使用final来提高方法调用效率。只有当您确定不希望重写该方法时,才将该方法设置为final。
String类使用char属性数组来保存String对象。
让我们看看一些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;
int off = offset;
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;
从上面的三个方法可以看出,子操作、连接操作和替换操作都不会对原始字符串执行,而是重新生成一个新的字符串对象。也就是说,原始字符串没有改变。
有一件事要永远记住:
对String的任何更改都不会影响原始对象,任何相关的更改操作都会生成新的对象。
现在您已经了解了String类的基础知识,让我们看看一些在常见使用中容易被忽视和混淆的领域。
想要系统学习JAVA推荐JAVA300集
Java300集零基础适合初学者视频教程←点击



