java对字符串子字符串方法的困惑
我有个问题。我在博客上读到了关于子串的内容。下面引用它
One point which is worth remembering here is that substring is also backed up by character array, which is used by original String. This can be dangerous if original string object is very large and substring is very small, because even a small fraction can hold reference of complete array and prevents it from being garbage collected even if there is no other reference for that particular String
我不明白说一个小参考可以防止垃圾收集是什么意思。有人能解释一下这个概念吗?谢谢
# 1 楼答案
我相信这个链接回答了你的问题:
Will a substring of another string prevent the parent string from being garbage collected?
此外:
正如Sotirios Delimanolis所说:Java 7或更高版本不再如此:
Java 7 String - substring complexity
# 2 楼答案
这意味着,由于
substring()
操作而创建的所有新字符串都包含对原始字符串中字符数组的引用,并且原始字符数组不会被垃圾收集,直到从它派生的所有子字符串也被垃圾收集,无论它们是大还是小正如评论中指出的,这种情况在Java的最新版本(1.7.0_06及更新版本)中没有出现。请参见此link以获取解释,但简而言之:现在
substring()
每次都会创建一个新字符串,因此底层char[]
不再被共享