有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我不明白说一个小参考可以防止垃圾收集是什么意思。有人能解释一下这个概念吗?谢谢


共 (2) 个答案

  1. # 1 楼答案

    我相信这个链接回答了你的问题:

    Will a substring of another string prevent the parent string from being garbage collected?

    // Example 1
    String samplel = "ToBeGarbageCollected";
    String sample2 = samplel.substring(0, 1);
    
    // Example 2
    String samplel = "ToBeGarbageCollected";
    String sample2 = new String(samplel.substring(0, 1));
    

    The substring method doesn't put a reference to the original String in the new String. What it actually does is save a reference to the original String's backing array; i.e the array that holds the characters.

    ... The original String's entire backing array will be remain reachable ... and that means it won't be a candidate for garbage collection.

    But there is another complication. You set sample1 to a String literal, and the String object that represents a String literal is always reachable (unless the entire class gets unloaded!)

    In your second example, copying the substring causes a new String to be created. And it is guaranteed that the new String won't share the backing array with the original String and the temporary substring

    此外:

    正如Sotirios Delimanolis所说:Java 7或更高版本不再如此:

    Java 7 String - substring complexity

  2. # 2 楼答案

    这意味着,由于substring()操作而创建的所有新字符串都包含对原始字符串中字符数组的引用,并且原始字符数组不会被垃圾收集,直到从它派生的所有子字符串也被垃圾收集,无论它们是大还是小

    正如评论中指出的,这种情况在Java的最新版本(1.7.0_06及更新版本)中没有出现。请参见此link以获取解释,但简而言之:现在substring()每次都会创建一个新字符串,因此底层char[]不再被共享