当调用一个方法对一个String对象进行操作时,比如说,
String s="hello world";
s.substring(6,7);
此时常量区会又多分配了一个对象"wo"的空间,但是不知道这个方法内有没有
对字符串进行其他操作,有没有产生新的字符串,怎么看?要去查看substring()方法的源码吗?
String s="hello world";
s.substring(6,7);
此时常量区会又多分配了一个对象"wo"的空间,但是不知道这个方法内有没有
对字符串进行其他操作,有没有产生新的字符串,怎么看?要去查看substring()方法的源码吗?
确定是这样?
substring没看源码,我想实现也就是一个new stringbuffer,然后遍历字符串,把startindex到endindex之间的char append到stringbuffer,最后返回stringbuffer.tostring
* Returns a new string that is a substring of this string. The
* substring begins at the specified <code>beginIndex</code> and
* extends to the character at index <code>endIndex - 1</code>.
* Thus the length of the substring is <code>endIndex-beginIndex</code>.
* <p>
* Examples:
* <blockquote><pre>
* "hamburger".substring(4, 8) returns "urge"
* "smiles".substring(1, 5) returns "mile"
* </pre></blockquote>
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @return the specified substring.
* @exception IndexOutOfBoundsException if the
* <code>beginIndex</code> is negative, or
* <code>endIndex</code> is larger than the length of
* this <code>String</code> object, or
* <code>beginIndex</code> is larger than
* <code>endIndex</code>.
*/
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);
}
应该定义一个新的String类型来接受s.substring(6,7);
比如是String s1=s.substring(6,7);
这就是说会在对象池中创建一个新的对象
这个的确在池中生成了一个新的string对象,但是没有被引用,所以会被GC干掉
s.substring(6,7);结果只有w没有o
s.substring(6,7);
system.out.print(s);
这是输出的结果为hello world,也就是说s.subString()这个方法,没有产生了新的对象,输出的字符还是没发生改变,因为string类是常量类,
s.subString()这个只是对string的副本进行操作,所以本身的值没有改变。
但是:
String s="hello world";
s=s.substring(6,7);
system.out.print(s);
这是对输出的值为wo。
string对象的核心还是一字符数组char[] value
对"hello world"调用substring(6,7)后返回了一个新对象,其字符数组value没变(这不就是说其占用的空间并没有减少..MGD!),只是把指针offset变成6,字符串长度变成了(7-6)=1
没事还是要多看看源码啊..
如果想改变字符串的内容,请使用StringBuffer类或StringBuilder类。