本文适合有一定java基础的同学。本博客宗旨:突出重点,分析难点。
The nature of string
First look at the string source code
public final class string Span class= "Hljs-keyword" >implements java . io . serializable , comparable < string , charsequence { /** The value is used for character storage. */ private final char value[]; /** Cache the hash code for the string */ private int hash; //Default to 0 ...}
The string class name is preceded by the final fix, and the variable char value[] is also the final decoration.
You can get three points:
- String is essentially a character array;
- The class cannot be inherited;
- Immutability (immutable).
Constant pool
The constant pool in Java is actually divided into two forms: a static constant pool and a run-time pool .
- A static constant pool, a constant pool in a *.class file, a constant pool in a class file that contains not only string literals, but also classes, methods, and most of the space in a class file.
- running A constant pool is the JVM virtual machine loading the constant pool in the class file into memory and saving it in the method area, which is what we often refer to as the run-time pool in the method area, after the classes mount operation is completed.
public class stringtest { public static void main (string[] args) {String s = new stri Ng ( "abc" ); String S1 = "abc" ; String s2 = "abc" ; String s3 = S.intern (); System.out.println (s = = S1); //false System.out.println (s = = s2); //false System.out.println (s = = S3); //false System.out.println (S1 = = S3); //true }}
Analysis:
Output as shown in the comments, the first two results have been said very clearly, and now take the last note, first look at s3 = S.intern () This sentence, when the call S.intern () This sentence, first go to the string constant pool to find, whether there is ABC this string, if not, then add, Returns a reference, if any, that already exists, where both S1 and S2 point to the ABC object in the constant pool, so here is the presence, after calling S.intern (), S3 and S1 and S2 point to the same object, so S1==s3 returns True.
Intern () has done a very unusual behavior: dynamically creating objects in the method area at run time, typically only the new keyword can create objects on the heap at run time, so here's a special one. The concept of a timely compilation.
If you are interested in constant pool, see: "Schematic diagram of Java Virtual machine" 2.2, Chang detailed (above)
Common methods Equals method
Public Boolean equals(Object AnObject) {if( This= = AnObject) {return true; }if(AnObjectinstanceofString) {String anotherstring = (string) anobject;intn = count;if(n = = anotherstring.count) {CharV1[] = value;//---------1--------- CharV2[] = Anotherstring.value;//-------2---------- inti = offset;intj = Anotherstring.offset; while(n--! =0) {//--------3------------ if(v1[i++]! = v2[j++])return false; }return true; } }return false; }
By 1 and 2 get two strings of character array, loop 3 for comparison.
The later articles will be individually explained by overriding the Equals and hashcode
CharAt
Gets the character at the specified position.
publiccharcharAt(int index) { if0) || (index >= value.length)) { thrownew StringIndexOutOfBoundsException(index); } return value[index]; }
Substring
Used to intercept strings
PublicStringsubstring(intBeginindex,intEndIndex) {if(Beginindex <0) {Throw NewStringindexoutofboundsexception (Beginindex); }if(EndIndex > Value.length) {Throw NewStringindexoutofboundsexception (EndIndex); }intSublen = Endindex-beginindex;if(Sublen <0) {Throw NewStringindexoutofboundsexception (Sublen); }return(Beginindex = =0) && (EndIndex = = value.length))? This:NewString (value, Beginindex, Sublen); }
Take a look at the new String (value, Beginindex, Sublen) source code
Public String(CharValue[],intOffsetintCount) {if(Offset <0) {Throw NewStringindexoutofboundsexception (offset); }if(Count <0) {Throw NewStringindexoutofboundsexception (count); }//Note:offset or count might be near-1>>>1. if(Offset > Value.length-count) {Throw NewStringindexoutofboundsexception (offset + count); } This. Value = Arrays.copyofrange (value, offset, offset+count); }
There is a arrays.copyofrange (value, offset, offset+count); the approximate meaning of this method is to copy a new copy of the string from the original character array.
如果还需要了解那个方法的底层代码可以给我留言。
The difference between StringBuffer and StringBuilder
Both StringBuffer and StringBuilder inherit the abstract class Abstractstringbuilder, which, like string, also defines char[] value and int count, but unlike the String class, They do not have a final modifier . Therefore, it is concluded that string, StringBuffer, and StringBuilder are essentially character arrays, but that when a connection operation is performed, thestring returns a new string instance each time. The Append method of StringBuffer and StringBuilder directly returnsthis, so this is why it is not recommended to use string when doing a large number of string join operations. StringBuffer and StringBuilder are recommended.
publicsynchronizedappend(String str) { super.append(i); returnthis; }
publicappend(String str) { super.append(str); returnthis; }
Because the StringBuffer method has synchronized all is readily available and safe.
Continue to see super.append (i); Source
publicappend(String str) { ifnull"null"; int len = str.length(); ensureCapacityInternal(count + len); str.getChars(0, len, value, count); count += len; returnthis; }
As an example of StringBuilder, it integrates abstractstringbuilder abstract classes. ensurecapacityinternal (count + len); is to check whether the length of the array after the addition of the previous character array length satisfies append. If no processing is satisfied, the creation of a new character array, if not satisfied, is twice times the length of the existing array, and the existing array is copied to the newly created array. Take a look at Str.getchars (0, Len, value, count); Source
Public void GetChars(intSrcbegin,intSrcend,CharDst[],intDstbegin) {if(Srcbegin <0) {Throw NewStringindexoutofboundsexception (Srcbegin); }if(Srcend > Value.length) {Throw NewStringindexoutofboundsexception (Srcend); }if(Srcbegin > Srcend) {Throw NewStringindexoutofboundsexception (Srcend-srcbegin); } system.arraycopy (value, Srcbegin, DST, Dstbegin, Srcend-srcbegin); }
See system.arraycopy (Value, Srcbegin, DST, Dstbegin, srcend-srcbegin); is to copy the new string into the original string.
Arraycopy Method Description:
publicstaticvoidarraycopyintintint length)
- SRC: source array;
- Srcpos: The starting position of the source array to be copied;
- Dest: an object array;
- Destpos: The starting position of the destination array placement;
- Ength: The length of the copy.
Note: Both SRC and dest must be of the same type or an array of types that can be converted. The interesting thing is that this function can achieve itself to copy, for example: int[] Fun ={0,1,2,3,4,5,6}; System.arraycopy (fun,0,fun,3,3); The result is: {0,1,2,0,1,2,6}; The implementation process is like this, Sir, as a temporary array of length, copy the data from Srcpos to srcpos+length-1 in the fun array into a temporary array, and then execute the system.arraycopy (temporary array, 0,fun,3,3).
Interesting study questions.
Have time to fill up.
Java basics of Java perplexed-String