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.
int off = original.offset;
v = Arrays.copyOfRange(originalValue, off, off+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;
}
不太明白该构造方法中if语句什么情况下会执行,原始的对象original.count什么情况下会与original.value这个数组的长度不相等呢,希望各位大侠赐教?
String a = "123456";
String b = a.substring(2);
String c = new String(b);
参考jdk 1.6的实现trim,subString等方法都会导致这种情况
1.8实现方式已经变了
如果字符串和原来的相同,就不执行if了(多个相同字符串共享相同的数组),当对字符串调用trim的时候,会走if拷贝一份,避免影响别的实例。
Perhaps this constructor is being called in order to trim the baggage, so make a copy of the array.
original这个值可能有空格,前缀有空格时就会调到本分支