[img]http://dl.iteye.com/upload/attachment/507335/259b78ef-0c45-35c9-9122-45eb00c370be.bmp[/img]
调试遇到:
s=""
但是value确是[j,d,b,c...............................],搞不懂了。高手来解答一下。
其实这是用String的方法substring出来的。substring方法做了优化处理,为了不重新new string对象增加系统开销,所以直接就用原来字符串的char数组,仅仅是改变string内部对象的offset和count。
你可以试试下面的code
[code="java"]
String a = "abcdefghijk";
String b = a.substring(a.length());
System.out.println(b);
[/code]
你会发现b跟你调试的一样
这个String类是只读类,故可以共享的。
String s="";
其实,只要是count字段为0了,都满足空字符串的要求,其他的不重要了。
[quote]
这个String类是只读类,故可以共享的。
[/quote]
不太理解,为啥这个String类是只读类?只读类是什么?
可以看的出来,在JVM中String是以char数组表示的。
String 类的Length()方法,就返回当前字符串的长度,
内部定义:public final class String
final 修饰的类是不能被继承的
就是讲只要是String的实例产生了,永远都不可能通过代码,将它值再进行改变了。
[quote]其实这是用String的方法substring出来的。substring方法做了优化处理,为了不重新new string对象增加系统开销,所以直接就用原来字符串的char数组,仅仅是改变string内部对象的offset和count。
你可以试试下面的code
Java代码
String a = "abcdefghijk";
String b = a.substring(a.length());
System.out.println(b);
你会发现b跟你调试的一样[/quote]
测试发现的确是的。
[code="java"]
public String substring(int i, int j)
{
if (i < 0)
throw new StringIndexOutOfBoundsException(i);
if (j > count)
throw new StringIndexOutOfBoundsException(j);
if (i > j)
throw new StringIndexOutOfBoundsException(j - i);
else
return i != 0 || j != count ? new String(offset + i, j - i, value) : this;
}
[/code]
这是String的substring内部的实现。
其中
[code="java"]new String(offset + i, j - i, value)[/code]
这段代码所用的构造函数是package型的,即同一个包的中其他类可以构造此类的对象。
[code="java"]
String(int i, int j, char ac[])
{
value = ac;
offset = i;
count = j;
}
[/code]