ホームページ  >  記事  >  Java  >  Java Stringのソースコード解釈を共有する

Java Stringのソースコード解釈を共有する

零下一度
零下一度オリジナル
2017-05-22 11:06:531392ブラウズ

Java String の部分的なソースコードの解釈に関する記事を理解するには、エディタに従ってください

String 型メンバー変数

/** 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;

上記のメンバー変数を使用すると、 String クラスは Final 型なので変更できないため、値が変更される限り、String データの格納は必ずしも配列の 0 番目の要素から開始されるわけではありません。 offset が指す要素。

たとえば、次のコードは新しいオブジェクトを生成し、最終結果は新しい値「bbaa」を持つ新しい文字列値になります。

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

String型オブジェクトの長さは不変であるとも言えます。文字列結合文字列は毎回新しいオブジェクトを生成するため、文字列結合の効率は可変長のStringBufferやStringBuilderほど速くないことは間違いありません。

ただし、次の状況では 2 つの文字列がすぐに結合されます:

    String a = "aa" + "bb";

その理由は次のとおりです。Java は文字列の結合に対して小さな最適化を行っており、"aa" と "bb" を直接結合して "aabb" にしています。 " を指定して値を a に代入すると、String オブジェクトを 1 回生成するだけで済みます。これにより、上記の方法と比較して String を生成する手間が 2 回節約され、明らかに効率が向上します。

String の一般的な 構築メソッドをいくつか見てみましょう

1. パラメーターなしの構築メソッド:

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

2. String 型オブジェクトの構築メソッドを渡します

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. Pass のコンストラクターを入力します。文字配列

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

4. 文字列番号、開始要素、および要素数のコンストラクターを渡します

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);
    }

上記の一般的なコンストラクターから、オブジェクトを作成するときに String を生成していることがわかります。完全な String 型を取得できるように、offset、count、value の 3 つの属性をオブジェクトに割り当てる必要があります。

共通関数:

1. 2 つの文字列が等しいかどうかを判断する関数 (Equal): 実際には、まず比較インスタンスが String 型データであるかどうかを判断し、そうでない場合は False を返します。それらの各文字要素は同じですか? 同じであれば True を返し、それ以外の場合は 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;
    }

2. 2 つの文字列のサイズを比較する関数 (compareTo): 入力は 2 つの文字列です。 0 が返された場合は、2 つの文字列の値が同じであることを意味します。0 より小さい場合は、最初の文字列の値が 2 番目の文字列の値より小さいことを意味し、0 より大きい場合は、最初の文字列の値が 2 番目の文字列の値より大きいことを意味します。 2 番目の文字列の値。

比較プロセスは主に次のとおりです。2 つの文字列の最初の要素から開始して、実際の比較は 2 つの文字の ACII コードです。異なる値が追加された場合は、最初の異なる値の差分が返されます。 、それ以外の場合は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;
    }

コードを表示

3. 文字列がプレフィックス文字列で始まり、toffsetが同じ長さであるかどうかを判断します

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. 2つの文字列を接続します(連結)

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);
    }

連結された文字列の数1. 最も直接的で、+ 接続を直接使用します

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

2. concat (String) メソッドを使用します

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

3. StringBuilder を使用します

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

1 つ目と 2 つ目はよく使用されますが、効率が比較的悪いため、StringBuilder を使用しますスプライシング効率が高くなります。

【関連する推奨事項】


1.

String は Java のオブジェクトですか?それともクラスですか? JavaのStringについて詳しく解説

2.

JavaのStringクラスのサンプルチュートリアルのまとめ

3. JavaのStringクラスの一般的なメソッドとは何ですか? Java の String クラスの一般的なメソッドをまとめます

4 Java の String クラスのサンプル チュートリアルを共有します

以上がJava Stringのソースコード解釈を共有するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。