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);
}
示例:
String string = "abcdef";
String subString = string.substring(1, 3);
string = null;
最后虽然将String赋值为null,但是subString仍然引用了最初的string,将不会被垃圾回收 。
在JDK 7之后,String的实现
public String(char value[], int offset, int count) {
//check boundary
this.value = Arrays.copyOfRange(value, off
本文探讨了JDK 6中String的substring()方法可能导致内存泄露的问题,由于该方法创建的子字符串仍引用原始字符串,导致无法被垃圾回收。而在JDK 7及以后的版本,这个问题通过Arrays.copyOfRange的改进得到了解决,避免了内存泄露的情况。
订阅专栏 解锁全文
1840

被折叠的 条评论
为什么被折叠?



