public String substring(int beginIndex, int endIndex)
使用这个方法,"smiles".substring(1, 5) 返回结果 "mile"
通过这个介绍我们基本了解了substring的作用,这样便于我们理解下面的内容。
准备工作
因为这个问题出现的情况在Java 6,如果你的Java版本号不是Java 6 需要调整一下。
终端调整(适用于Mac系统)
查看java版本号
1234
13:03 $ java -versionjava version "1.8.0_25"Java(TM) SE Runtime Environment (build 1.8.0_25-b17)Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)
public class TestGC { private String largeString = new String(new byte[100000]); String getString() { return this.largeString.substring(0,2); } public static void main(String[] args) { java.util.ArrayList list = new java.util.ArrayList(); for (int i = 0; i < 1000000; i++) { TestGC gc = new TestGC(); list.add(gc.getString()); } }}
public class TestGC { private String largeString = new String(new byte[100000]); String getString() { //return this.largeString.substring(0,2); return new String("ab"); } public static void main(String[] args) { java.util.ArrayList list = new java.util.ArrayList(); for (int i = 0; i < 1000000; i++) { TestGC gc = new TestGC(); list.add(gc.getString()); } }}
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;}
public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > value.length) { throw new StringIndexOutOfBoundsException(endIndex); } int subLen = endIndex - beginIndex; if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } return ((beginIndex == 0) && (endIndex == value.length)) ? this : new String(value, beginIndex, subLen);}
substring方法中调用的构造方法,进行内容字符数组复制。
12345678910111213
public String(char value[], int offset, int count) { if (offset < 0) { throw new StringIndexOutOfBoundsException(offset); } if (count < 0) { throw new StringIndexOutOfBoundsException(count); } // 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);}