在JDK6中,这个方法只会在标识现有字符串的字符数组上 给一个窗口来表示结果字符串,但是不会创建一个新的字符串对象。如果需要创建个新字符串对象,可以这样在结果后面+一个空的字符串:
Oracle JDK7中的substring()方法会创建一个新的字符数组,而不用之前存在的。
substring() in JDK 6:
- //JDK 6
- String(int offset, int count, char value[]) {
- this.value = value;
- this.offset = offset;
- this.count = count;
- }
-
- public String substring(int beginIndex, int endIndex) {
- //check boundary
- return new String(offset + beginIndex, endIndex - beginIndex, value);
- }
复制代码 substring() in JDK 7:
- //JDK 7
- public String(char value[], int offset, int count) {
- //check boundary
- this.value = Arrays.copyOfRange(value, offset, offset + count);
- }
-
- public String substring(int beginIndex, int endIndex) {
- //check boundary
- int subLen = endIndex - beginIndex;
- return new String(value, beginIndex, subLen);
- }
复制代码
参考:http://www.programcreek.com/2013/09/the-substring-method-in-jdk-6-and-jdk-7/
|
|