-
// JDK6,包级私有构造,共享 value数组提升速度 String(int offset, int count, char value[]) { this.value = value; this.offset = offset; this.count = count; } public String substring(int beginIndex, int endIndex) { // ... 检查边界的代码 // 如果范围和自己一模一样,则返回自身,否则用value字符数组构造一个新的对象 return ((beginIndex == 0) && (endIndex == count)) ? this : new String(offset + beginIndex, endIndex - beginIndex, value); }
JDK6中value对象不变,只是offset和count 的两个属性值发生了变化
-
public String substring(int i, int j) { if(i < 0) throw new StringIndexOutOfBoundsException(i); if(j > value.length) throw new StringIndexOutOfBoundsException(j); int k = j - i; if(k < 0) throw new StringIndexOutOfBoundsException(k); else return i != 0 || j != value.length ? new String(value, i, k) : this; }
public String(char ac[], int i, int j) { if(i < 0) throw new StringIndexOutOfBoundsException(i); if(j <= 0) { if(j < 0) throw new StringIndexOutOfBoundsException(j); if(i <= ac.length) { value = "".value; return; } } if(i > ac.length - j) { throw new StringIndexOutOfBoundsException(i + j); } else { value = Arrays.copyOfRange(ac, i, i + j); return; } }
public String(char ac[], int i, int j) { if(i < 0) throw new StringIndexOutOfBoundsException(i); if(j <= 0) { if(j < 0) throw new StringIndexOutOfBoundsException(j); if(i <= ac.length) { value = "".value; return; } } if(i > ac.length - j) { throw new StringIndexOutOfBoundsException(i + j); } else { value = Arrays.copyOfRange(ac, i, i + j); return; } }
JDK7中真实地在堆内存中创建了另一个字符数组.