Lucky to go to Sogou today, there is a very interesting question
String str1 = "test for Sougou"; String str2 = str1.substring (5);
Test Center is whether STR2 generates a new character array to save "for Sougou"
At that time I thought string inside was encapsulated a char[], cannot be like CPP as the first address plus a number to do char[] reuse
The new string must be arraycopy once to implement the SUBSTRING function, so there must be new memory generation
Came back to see the realization of
Because Android Studio was on, it looked under Android under the String.substring implementation, and sent to the classmate
Public String substring (int start) { if (start = = 0) { return this; } If (Start >= 0 && start <= count) { return new String (offset + start, count-start, value); } Throw Indexandlength (start); }
String (int offset, int charcount, char[] chars) { this.value = chars; This.offset = offset; This.count = charcount; }
Use the member variable offset to save the next offset, directly to the char[] reference to the new string, no memory requested
Sigh good subtle realization at the same time, find yourself doing wrong
Who knows the classmate read the source code after asked me what version of the JDK, and his side of the implementation is not the same
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); }
Public String (char value[], int offset, int count) { if (offset < 0) { throw new Stringindexoutofboundsexceptio n (offset); } if (Count < 0) { throw new stringindexoutofboundsexception (count); } Note:offset or count might be near-1>>>1. if (Offset > Value.length-count) { throw new Stringindexoutofboundsexception (offset + count); } This.value = Arrays.copyofrange (value, offset, offset+count); }
In addition to Beginindex=0 is directly returned to the current outside, all others are arraycopy
Yes!!! New memory in JDK!!!
It must be said that Google programmers are really
Different implementations of string.substring in Android and Java