Java string Part source code parsing

Source: Internet
Author: User
Tags first string

member variable of type string

/**property value of String*/      Private Final Charvalue[]; /**The offset is the first index of the storage, which is used.*/    /**the starting position where the array is used **/    Private Final intoffset; /**The count is the number of characters in the String.*/    /**number of elements in String **/    Private Final intcount; /**Cache The hash code for the string*/   /**hash value of String type **/    Private intHash//Default to 0    /**Use serialversionuid from JDK 1.0.2 for interoperability*/    Private Static Final LongSerialversionuid = -6849794470754667710l;

With the member variable above, you know that the value of the string class is final and cannot be changed, so as long as a value changes, a new string object is generated, and the string data is stored not necessarily from the No. 0 element of the array, but from the element that offset refers to.

As the following code generates a new object, the last one is a new string value of "Bbaa".

     New String ("BB");      New String ("AA");      =  A + b;    

It can also be said that the string type object is the length immutable, string concatenation string each time to produce a new object, so the concatenation string efficiency certainly does not have the variable length StringBuffer and StringBuilder fast.

However, the following is a quick concatenation of two strings:

    String a = "AA" + "BB";

The reason is: Java to its string splicing has been a small optimization, he is directly "AA" and "BB" directly stitching into "AABB", and then assign the value to a, just create a string object, than the above way to reduce 2 times the generation of string, the efficiency is significantly higher.

Let's take a look at some of the common construction methods of String.

1, no parameters of the construction method:

 Public String () {    this. offset = 0;      this. Count = 0;      This New Char [0];    }

2, passing in a Sring type Object construction method

 Publicstring (string original) {intSize =Original.count; Char[] OriginalValue =Original.value; Char[] v; if(Originalvalue.length >size) {         //The array representing the String is bigger than the new//String itself. Perhaps this constructor is being called//in order to trim the baggage, so make a copy of the array.            intOff =Original.offset; V= Arrays.copyofrange (OriginalValue, off, off+size); } Else {         //The array representing the String is the same//size as the String, so no point in making a copy.v =OriginalValue; }     This. Offset = 0;  This. Count =size;  This. Value =v; }

3. Constructor for passing in a character array

 Public String (char  value[]) {    int size = value.length;     this. offset = 0;     this. Count = size;     this. Value = arrays.copyof (value, size);    }

4, the constructor that passes in a string number, and the start element, the number of elements

 PublicString (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. Offset = 0;  This. Count =count;  This. Value = Arrays.copyofrange (value, offset, offset+count); }

As can be seen from the several common constructors above, we must assign the offset, count, value three properties of the object when generating a string object so that we can obtain a completed string type.

Common functions:

1. A function that determines whether the two strings are equal (Equal): In fact, it is the first to judge whether the instance of comparison is a string type of data, not to return false, is to compare each of their character elements is the same, if all the same return true, otherwise returns false

 Public Booleanequals (Object anobject) {if( This==anobject) {     return true; } if(AnObjectinstanceofString) {String anotherstring=(String) AnObject; intn =count; if(n = =anotherstring.count) {CharV1[] =value; CharV2[] =Anotherstring.value; inti =offset; intj =Anotherstring.offset;  while(n--! = 0) {      if(v1[i++]! = v2[j++])   return false; }  return true; } } return false; }

2. Compare the function of two string size (compareTo): input is two string, return 0 for two string value same, return less than 0 is the value of the first string less than the second string, greater than 0 means the value of the first string is greater than the value of the second string.

The process of comparison is mainly as follows: Starting from the first element of the two strings, the actual comparison is two char acii code, adding a different value, return the difference of the first different value, otherwise return 0

 Public intcompareTo (String anotherstring) {intLen1 =count;intLen2 =Anotherstring.count;intn =math.min (Len1, len2);CharV1[] =value;CharV2[] =Anotherstring.value;inti =offset;intj =Anotherstring.offset;if(i = =j) {intK =i; intLim = n +i;  while(K <Lim) {CharC1 =V1[k]; CharC2 =V2[k]; if(C1! =C2) {      returnC1-C2; } k++; } } Else {      while(n--! = 0) {  CharC1 = v1[i++]; CharC2 = v2[j++]; if(C1! =C2) {      returnC1-C2; }     } } returnLEN1-Len2; }
View Code

3. Determine if a string begins with a prefix string, Toffset is the same length

 Public BooleanStartsWith (String prefix,intToffset) { CharTa[] =value;intto = offset +Toffset;CharPa[] =Prefix.value;intPO =Prefix.offset;intPC =Prefix.count;//Note:toffset might be near-1>>>1. if((Toffset < 0) | | (Toffset > Count-pc)) {     return false; }  while(--pc >= 0) {     if(ta[to++]! = pa[po++]) {         return false; } } return true; }  Public inthashcode () {inth =Hash;if(H = = 0) {     intOff =offset; CharVal[] =value; intLen =count;  for(inti = 0; i < Len; i++) {h= 31*h + val[off++]; } Hash=h; }        returnh; }

4. Connect two strings (concat)

public intOtherlen =if (Otherlen = = 0)     {return    This charnewChar[count + Otherlen]; GetChars (0, Count, buf , 0); Str.getchars (0returnnew String (0, Count + Otherlen, buf);    }

Several ways to concatenate strings

1, the most direct, directly with + connection

     New String ("BB");      New String ("AA");      =  A + b;

2. Using the Concat (String) method

      New String ("BB");       New String ("AA");        = A.concat (b);

3. Using StringBuilder

New String ("BB"new string ("AA");      New StringBuffer (). append (a). Append (b);

The 12th is used more, but the efficiency is poor, the use of StringBuilder splicing efficiency is higher.

Java string Part source code parsing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.