Java String.substring method potential memory leak?

前端 未结 3 1453
灰色年华
灰色年华 2020-11-29 07:49

I was going through the String class API and looks like there is a potential memory leak caused by substring method as it shares same character array as original String.

3条回答
  •  [愿得一人]
    2020-11-29 08:08

    In Java 7, String's subString is modified to :

    /**
         * Returns a new string that is a substring of this string. The
         * substring begins with the character at the specified index and
         * extends to the end of this string. 

    * Examples: *

         * "unhappy".substring(2) returns "happy"
         * "Harbison".substring(3) returns "bison"
         * "emptiness".substring(9) returns "" (an empty string)
         * 
    * * @param beginIndex the beginning index, inclusive. * @return the specified substring. * @exception IndexOutOfBoundsException if * beginIndex is negative or larger than the * length of this String object. */ public String substring(int beginIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } int subLen = value.length - beginIndex; if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } return (beginIndex == 0) ? this : new String(value, beginIndex, subLen); }

    Hence, everytime you do subString with beginIndex NOT equal to 0, we have new String Object.

提交回复
热议问题