String内部维护的是一个数组如下: private final char value[]; 其length()方法返回的private final int count;这个东西。 每当生成一个String的时候这两个参数都是一定的。String a = "a"; a = a + "a"; 其实大家都知道是新产生了一个String,而a的引用指向这个String而已。 所以a可以获取他的count为1,而"a"的count也为1,产生的char value[] = {'a','a'}; count=2; 所以length就为2了
public String(String original) { int size = original.count; char[] originalValue = original.value; char[] v; if (originalValue.length > size) { // The array representing the String is bigger than the new // String itself. Perhaps this constructor is being called // in order to trim the baggage, so make a copy of the array. v = new char[size]; System.arraycopy(originalValue, original.offset, v, 0, size); } else { // The array representing the String is the same // size as the String, so no point in making a copy. v = originalValue; } this.offset = 0; this.count = size; this.value = v; }
private final char value[];
其length()方法返回的private final int count;这个东西。
每当生成一个String的时候这两个参数都是一定的。String a = "a";
a = a + "a";
其实大家都知道是新产生了一个String,而a的引用指向这个String而已。
所以a可以获取他的count为1,而"a"的count也为1,产生的char value[] = {'a','a'}; count=2;
所以length就为2了
return count;
}
int size = original.count;
char[] originalValue = original.value;
char[] v;
if (originalValue.length > size) {
// The array representing the String is bigger than the new
// String itself. Perhaps this constructor is being called
// in order to trim the baggage, so make a copy of the array.
v = new char[size];
System.arraycopy(originalValue, original.offset, v, 0, size);
} else {
// The array representing the String is the same
// size as the String, so no point in making a copy.
v = originalValue;
}
this.offset = 0;
this.count = size;
this.value = v;
}