Answers
1950 public String substring(int beginIndex, int endIndex) {
1951 if (beginIndex < 0) {
1952 throw new StringIndexOutOfBoundsException(beginIndex);
1953 }
1954 if (endIndex > count) {
1955 throw new StringIndexOutOfBoundsException(endIndex);
1956 }
1957 if (beginIndex > endIndex) {
1958 throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
1959 }
1960 return ((beginIndex == 0) && (endIndex == count)) ? this :
1961 new String(offset + beginIndex, endIndex - beginIndex, value);
1962 }
1963
看了下源码,substring实际上底层还是引用原字符串的value:char[],这样原字符串无法被回收,比较耗费存储,尾部加""之后会创建一个新字符串,原字符串可以被回收,新字符串长度比较小,相比起来节省存储一些。其实没有很节省内存,看你的具体应用场景。
jlspzw
answered 12 years, 11 months ago