String的构造函数
String
有很多构造函数,不同种类的有不同的作用,接下来我们一个个看下去
- 1
public String() {
this.value = "".value;
}
初始化一个String
对象,使其表示一个空字符串序列,由于字符串的不可变性,这个方法其实是不必要的。
- 2
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
简单易懂,除非需要显式复制,否则这个方法也是不必要,因为字符串的不可变性。
- 3
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
依然很简单,不过要注意字符数组的后续修改不会影响新创建的字符串。
- 4
public String(char value[], int offset, int count) {
if (offset < 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);
}
这个方法是从字符数组中截取一段作为value
的值,这里面做了一些关于长度与角标的判断,另外,同样的,这里形参char[]
的改变与其之前所创建的String
对象已经没有关系了
- 5