Home > Java > javaTutorial > body text

Share some source code interpretation of java String

零下一度
Release: 2017-05-22 11:06:53
Original
1444 people have browsed it

Take you to understand an article about java String partial source code interpretation, let’s take a look with the editor

Member variables of String type

/** String的属性值 */  
    private final char value[];    /** The offset is the first index of the storage that is used. */
    /**数组被使用的开始位置**/
    private final int offset;    /** The count is the number of characters in the String. */
    /**String中元素的个数**/
    private final int count;    /** Cache the hash code for the string */
   /**String类型的hash值**/
    private int hash; // Default to 0

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -6849794470754667710L;
Copy after login

With the above member variables, you can know that the value of the String class is final and cannot be changed, so as long as a value changes, a new String type object will be generated, and the String data does not necessarily start from the 0th position of the array. element, but starts from the element pointed to by offset.

The following code generates a new object, and 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;
Copy after login
Copy after login

It can also be said that the length of String type objects is immutable. String splicing strings will generate a new object every time, so the efficiency of string splicing is definitely not as fast as the variable length StringBuffer and StringBuilder. .

However, in the following situation, two strings are quickly spliced:

    String a = "aa" + "bb";
Copy after login

The reason is: Java has made a small optimization for its string splicing. It directly splices "aa" and "bb" are directly spliced ​​into "aabb", and then the value is assigned to a. The String object only needs to be generated once, which saves two times of generating String compared to the above method, and is obviously much more efficient.

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

1. Parameterless construction method:

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

2. Pass in the constructor of a Sring type 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;
    }
Copy after login

3. Pass in 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);
    }
Copy after login

4. Pass in a string number and the starting element , Constructor of the 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);
    }
Copy after login

As can be seen from the above common constructors, when we generate a String object, we must assign values ​​to the three attributes of the object: offset, count, and value. , so that we can get a completed String type.

Common functions:

1. Function to determine whether two strings are equal (Equal): In fact, it is to first determine whether the comparison instance is String type data, not Then return False, if they compare each character element to see if they are the same, if they are the same, return True, otherwise return False

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;
    }
Copy after login

2. Function to compare the sizes of two strings (compareTo ): The input is two strings. The returned 0 means that the two strings have the same value. If the return is less than 0, the value of the first string is less than the value of the second string. If it is greater than 0, it means the first string. The value is greater than the value of the second string.

The comparison process is mainly as follows: starting from the first element of the two strings, the actual comparison is the ACII code of the two chars. If different values ​​are added, the first different value will be returned. Difference, otherwise return 0

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;
    }
Copy after login

View Code

3. Determine whether a string starts with a prefix string, and tooffset is 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;
    }
Copy after login

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);
    }
Copy after login

Several ways to connect strings

1. The most direct, use + to connect directly

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

2. Use the concat (String) method

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

3. Use StringBuilder

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

It is used more often in the first and second methods, but the efficiency is relatively poor. The efficiency of using StringBuilder for splicing is higher.

[Related recommendations]

1. Is String an object or a class in java? Detailed explanation of String in java

2. Summary of the example tutorials of String class in Java

3. What are the common methods of String class in Java ? Summarize the common methods of String class in Java

4. Share example tutorials of String class in Java

The above is the detailed content of Share some source code interpretation of java String. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!