Java String source code parsing, javastring

Source: Internet
Author: User

Java String source code parsing, javastring

String typeMember variables

/** String attribute value */private final char value [];/** The offset is the first index of the storage that is used. * // ** start position of The array used **/private final int offset;/** the count is the number of characters in The String. * // ** number of elements in String **/private final int count; /** Cache the hash code for the string * // ** hash value of the String type **/private int hash; // Default to 0/** use serialVersionUID from JDK 1.0.2 for interoperability */private static final long serialVersionUID =-6849794470754667710L;

The preceding member variables show that the values of the String class are of the final type and cannot be changed. Therefore, a new String type object will be generated if a value is changed, storing String data does not necessarily start from the first element of the array, but from the element indicated by the offset.

The following code generates a new object. The final result is a new String value with a new value of "bbaa.

     String a = new String("bb");     String b = new String("aa");     String c =  a + b;    

 

It can also be said that objects of the String type are immutable in length. Every time a String is concatenated, a new object is generated. Therefore, the efficiency of String concatenation is certainly not as fast as that of StringBuffer and StringBuilder.

 

However, in this case, two strings are quickly spliced:

    String a = "aa" + "bb";

The reason is: java has made a small Optimization on its String concatenation. He directly concatenates "aa" and "bb" into "aabb" and then assigns the value to, you only need to generate a String object once, which is much more efficient than generating a String twice in the preceding method.

 

 

Next let's take a look at several strings.Common ConstructorRight

 

1. Construction Method without parameters:

public String() {    this.offset = 0;    this.count = 0;    this.value = new char[0];    }

 

 

2. Input a constructor for a Sring object.

public String(String original) {    int size = 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.            int off = 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. input the constructor of a character array.

public String(char value[]) {    int size = value.length;    this.offset = 0;    this.count = size;    this.value = Arrays.copyOf(value, size);    }

 

 

4. Input a string number, a constructor with the Start Element and number of elements.

public String(char value[], int offset, int count) {        if (offset < 0) {            throw new StringIndexOutOfBoundsException(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.offset = 0;        this.count = count;        this.value = Arrays.copyOfRange(value, offset, offset+count);    }

 

As can be seen from several common constructors above, when we generate a String object, we must assign values to the offset, count, and value attributes of this object, in this way, we can obtain a complete String type.

 

 

Common functions:

 

1. Determine whether two strings are equal (Equal): In fact, it is to first determine whether the instance to be compared is String-type data. If not, False is returned. If they are the same, True is returned. Otherwise, False is returned.

public boolean equals(Object anObject) { if (this == anObject) {     return true; } if (anObject instanceof String) {     String anotherString = (String)anObject;     int n = count;     if (n == anotherString.count) {  char v1[] = value;  char v2[] = anotherString.value;  int i = offset;  int j = anotherString.offset;  while (n-- != 0) {      if (v1[i++] != v2[j++])   return false;  }  return true;     } } return false;    }

 

 

2. Compare two string-sized functions (CompareTo): The input is two strings. the return value 0 indicates that the two strings have the same value. If the return value is smaller than 0, the value of the first string is smaller than the value of the second string, if the value is greater than 0, the value of the first string is greater than that of the second string.

The comparison process is as follows: compare the two strings from the first element. The actual comparison is the ACII code of the two char strings, which has different values, returns the difference value of the first value. Otherwise, 0 is returned.

Public int compareTo (String anotherString) {int len1 = count; int len2 = anotherString. count; int n = Math. min (len1, len2); char v1 [] = value; char v2 [] = anotherString. value; int I = offset; int j = anotherString. offset; if (I = j) {int k = I; int lim = n + I; while (k <lim) {char c1 = v1 [k]; char c2 = v2 [k]; if (c1! = C2) {return c1-c2;} k ++ ;}} else {while (n --! = 0) {char c1 = v1 [I ++]; char c2 = v2 [j ++]; if (c1! = C2) {return c1-c2 ;}} return len1-len2 ;}View Code

 

 

3. Determine whether a string starts with a prefix string. toffset is of the same length.

public boolean startsWith(String prefix, int toffset) { char ta[] = value; int to = offset + toffset; char pa[] = prefix.value; int po = prefix.offset; int pc = 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 int hashCode() { int h = hash; if (h == 0) {     int off = offset;     char val[] = value;     int len = count;            for (int i = 0; i < len; i++) {                h = 31*h + val[off++];            }            hash = h;        }        return h;    }

 

 

4. connect two strings (concat)

public String concat(String str) { int otherLen = str.length(); if (otherLen == 0) {     return this; } char buf[] = new char[count + otherLen]; getChars(0, count, buf, 0); str.getChars(0, otherLen, buf, count); return new String(0, count + otherLen, buf);    }

 

 

Several Methods for connecting strings

1. Direct + connection

     String a = new String("bb");     String b = new String("aa");     String c =  a + b;

 

 

2. Use the concat (String) Method

      String a = new String("bb");      String b = new String("aa");       String d = a.concat(b);

 

 

3. Use StringBuilder

 String a = new String("bb"); String b = new String("aa");     StringBuffer buffer = new StringBuffer().append(a).append(b);

 

The first and second versions are used in a lot of ways, but the efficiency is relatively poor. The StringBuilder splicing is more efficient.

 

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.