When looking at the source code of string in Jdk6 recently, I found that there was a construction method of string, which contains the following sources:
public string (string original) {
int size = Original.count;
char[] OriginalValue = original.value;
Char[] v;
if (originalvalue.length > size) {
int off = Original.offset;
v = arrays.copyofrange (OriginalValue, off, off+size);
} else {
v = originalvalue;
}
This.offset = 0;
This.count = size;
This.value = v;
}
At this time on the originalvalue.length > Size this puzzled ah. Therefore, the Internet search for reasons. It was found that the problem was mentioned in the StackOverflow. There is also a domestic article also said the problem.
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/
1 http://stackoverflow.com/questions/12907986/how-could-originalvalue-length-size-happen-in-the-string-constructor
2 http://www.kankanews.com/ICkengine/archives/99041.shtml
After reading the two articles above, I thoroughly understand. So it is. Look at the substring method of string in Jdk6.
Public String substring (int beginindex, int endindex) {
if (Beginindex < 0) {
throw new Stringindexoutofboundse Xception (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);
}
Package private constructor which shares value array for speed.
String (int offset, int count, Char value[]) {
this.value = value;
This.offset = offset;
This.count = count;
}
Take a look at the above source code and find out whether a new string object's character array is used after the substring method or an array of characters from the original object. This shows the problem of originalvalue.length > size. Such as
String s1= "Hello World";
String s2=s1.substring (6);
String S3=new string (s2);
The
analyzes the properties of the above code S2 char[] value is still the original S1 attribute char[] value={' h ', ' e ', ' l ', ' l ', ' o ', ', ' w ', ' O ', ' r ', ' L ', ' d '}. The S2 property offset is 6,count to 5. originalvalue.length=11>count=5 when new String (S2). So we know that under such circumstances there will be problems discussed in this article.