>  기사  >  Java  >  Java String의 일부 소스 코드 해석을 공유합니다.

Java String의 일부 소스 코드 해석을 공유합니다.

零下一度
零下一度원래의
2017-05-22 11:06:531392검색

Java 문자열 부분 소스 코드 해석에 대한 기사를 살펴보고 편집기로 살펴보겠습니다.

문자열 유형의 멤버 변수

/** 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 클래스의 값은 최종적이며 변경할 수 없음을 알 수 있으므로 값이 변경되는 한 새로운 String 유형의 객체가 생성되고 String 데이터는 변경되지 않습니다. 반드시 배열 요소의 0번째 위치부터 시작할 필요는 없지만 오프셋이 가리키는 요소부터 시작합니다.

다음 코드는 새 개체를 생성하고 최종 결과는 새 값 "bbaa"를 포함하는 새 문자열 값입니다.

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

문자열 유형 객체의 길이는 불변이라고 할 수도 있습니다. 문자열 접합 문자열은 매번 새로운 객체를 생성하므로 문자열 접합 효율성은 확실히 가변 길이 StringBuffer 및 StringBuilder만큼 빠르지는 않습니다. .

그러나 다음 상황에서는 두 문자열이 빠르게 연결됩니다.

    String a = "aa" + "bb";

이유는 다음과 같습니다. Java는 문자열 연결을 위해 약간의 최적화를 수행했습니다. "aa"와 "bb". "aabb"에 직접 연결되고 값이 a에 할당됩니다. String 객체는 한 번만 생성하면 되며, 이는 위 방법에 비해 String 생성 시간을 두 배로 절약하고 분명히 훨씬 더 효율적입니다.

String

일반적인

구성 방법을 살펴보겠습니다. 1. 매개변수 없는 구성 방법:

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

2. 문자열 유형 객체

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. 문자 배열

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 객체를 생성할 때 객체의 세 가지 속성인 offset, count 및 value에 값을 할당해야 함을 알 수 있습니다. 그러면 완성된 String 유형을 얻을 수 있습니다.

공용 함수:

1. 두 문자열이 같은지 확인하는 함수(Equal): 실제로는 비교 인스턴스가 문자열 유형인지 먼저 확인하는 것입니다. data, not 그런 다음 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. 크기를 비교하는 함수 of two strings(compareTo ): 입력은 두 개의 문자열입니다. 반환된 0은 두 문자열의 값이 동일하다는 의미입니다. 반환이 0보다 작으면 첫 번째 문자열의 값이 값보다 작습니다. 두 번째 문자열의 값입니다. 0보다 크면 첫 번째 문자열의 값이 두 번째 문자열의 값보다 크다는 의미입니다.

비교 과정은 주로 다음과 같습니다. 두 문자열의 첫 번째 요소부터 시작하여 실제 비교는 두 문자의 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. 두 문자열 연결(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);
    }

문자열을 연결하는 여러 가지 방법

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. 자바에서는 문자열이 객체인가요, 클래스인가요? Java의 String에 대한 자세한 설명

2. Java의 String 클래스 예제 튜토리얼 요약

3. Java의 문자열 클래스? Java의 String 클래스의 일반적인 메소드 요약

4.

Java의 String 클래스 예제 튜토리얼 공유

위 내용은 Java String의 일부 소스 코드 해석을 공유합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.