前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java 的 String.substring 方法有什么问题?

Java 的 String.substring 方法有什么问题?

作者头像
水货程序员
修改2018-12-03 15:48:27
1.5K0
修改2018-12-03 15:48:27
举报
文章被收录于专栏:javathingsjavathings

在 Java 7, Update 6 之前,substring 方法会有内存泄漏的问题。

substring 会构造一个新的 string 对象,该 string 对象引用了原来的 string 对象的一个 char 数组。这会导致原有的 string 对象不会被垃圾回收。引发内存泄漏。

看源码:

代码语言:javascript
复制
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
    throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
    throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
    throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
 
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}

上面调用的构造方法如下:

代码语言:javascript
复制
//Package private constructor which shares value array for speed.
String(int offset, int count, char value[]) {
    this.value = value;
    this.offset = offset;
    this.count = count;
}

其中传入的 value 用的还是原来 string 对象的 value。即这个 value 的值会被两个 string 对象共享着。(String 类中的私有成员:private final char value[];  )

内存模型如下:

(图片来自于网络)
(图片来自于网络)

可以用如下代码规避:

String sub = new String(s.substring(…)); // create a new string

或者用更新版本的 JDK,在 JDK7 中,这个 value 值的赋值方式为:

this.value = Arrays.copyOfRange(value, offset, offset + count);

也不会有内存泄漏的问题。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档