JDK6中subString()的源码
01 | //JDK6 |
02 |
String( int offset, int count, char value[]){
|
03 |
this .value=value;
|
04 |
this .offset=offset;
|
05 |
this .count=count;
|
06 | } |
07 |
public Stringsubstring( int beginIndex, int endIndex){
|
08 |
//checkboundary
|
09 |
return new String(offset+beginIndex,endIndex-beginIndex,value);
|
10 | } |
实际上substring并没有去new 一个String对象,substring返回的字符串和之前的字符串是共用的一个字符数组。
只是数组的起点和长度改变了。所以之前的那个被截取的字符串就没有(也不能)被回收。
如果你想要让它能被回收,可以这样substring.
1 |
x.substring(a,b)+ ""
|
2 | //or |
3 |
new String(x.substring(a,b))
|
前者等同于:
1 |
StringBuildersb= new StringBuilder();
|
2 | sb.append(x.substring(x,y)); |
3 |
sb.append( "" );
|
4 | x=sb.toString(); |
所以,使用new String(x.substring(a,b))的方式效率更高。