专业的JAVA编程教程与资源

网站首页 > java教程 正文

每天积累一点点(Java基础——》String类学习——one day)

temp10 2024-10-01 22:30:51 java教程 15 ℃ 0 评论

一.String类总览

1)首先我们先大致看下String类的源码

每天积累一点点(Java基础——》String类学习——one day)

public final class String
 implements java.io.Serializable, Comparable<String>, CharSequence {
 /** The value is used for character storage. */
 private final char value[];
 /** Cache the hash code for the string */
 private int hash; // Default to 0
 /** use serialVersionUID from JDK 1.0.2 for interoperability */
 private static final long serialVersionUID = -6849794470754667710L;
 /**
 * Class String is special cased within the Serialization Stream Protocol.
 *
 * A String instance is written into an ObjectOutputStream according to
 * <a href="{@docRoot}/../platform/serialization/spec/output.html">
 * Object Serialization Specification, Section 6.2, "Stream Elements"</a>
 */
 private static final ObjectStreamField[] serialPersistentFields =
 new ObjectStreamField[0];
.....
}

可以看出String是一个被final修饰的类,则表示该类不能被继承,其成员方法也被final修饰,

还可以看出String类内部是由char数组实现字符串的。

2)我们再来看下常用的一些方法如subString(),concat(),replace()

//字符串连接方法
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);
}
//字符串截取方法
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);
}
//字符串替换方法
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;
}

由上我们可以看出在这些操作中都是new出了新的String对象,重新生成了一个字符串对象,原始对象并没有被改变。

通过观察其所有的字符串操作方法可以得出以下结论:

String对象一旦被创建就是固定不变的了,对String对象的任何改变都不影响到原对象, 相关的任何change操作都会生成新的对象。

对String类有了一个大概地了解之后明天我准备结合Java虚拟机的相关知识来深入的学习字符串常量池。

-------------爱篮球的coder

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表