java-substring

1 String x = "abcdef";
2 x = x.substring(1,3);
3 System.out.println(x);//输出bc

来看jdk6中String的substring

 1 //JDK 6
 2 //该构造器非公开
 3 String(int offset, int count, char value[]) {
 4     this.value = value;
 5     this.offset = offset;
 6     this.count = count;
 7 }
 8  
 9 public String substring(int beginIndex, int endIndex) {
10     //check boundary
11     return  new String(offset + beginIndex, endIndex - beginIndex, value);
12 }

 jdk6中substring确实新创建了一个String对象,但问题在于该对象的char[] value字段仍然是旧String对象的(新瓶装旧酒),设想如果就string很长,新string很短,这就造成了内存泄漏

一种解决方法

x = x.substring(x, y) + ""//最终会创建新的char[]

再来看jdk7的substring

 1 //JDK 7
 2 //其实在jdk6中就有该构造器,只不过substring未调用
 3 public String(char value[], int offset, int count) {
 4     //check boundary
 5     this.value = Arrays.copyOfRange(value, offset, offset + count);//一份全新的拷贝
 6 }
 7  
 8 public String substring(int beginIndex, int endIndex) {
 9     //check boundary
10     int subLen = endIndex - beginIndex;
11     return new String(value, beginIndex, subLen);
12 }

参考:https://www.programcreek.com/2013/09/the-substring-method-in-jdk-6-and-jdk-7/

原文地址:https://www.cnblogs.com/holoyong/p/7507865.html