Java 源码 - String


介绍

The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are constant, their values cannot be changed after they are created.

示例

public class Test {
  public static void main(String[] args) {
    char data[] = {'a', 'b', 'c'};
    String str = new String(data);
    System.out.println(str);
  }
}

源码

public final class String implements Serializable, Comparable, CharSequence {

  private final char value[];

  private int hash;

  public String(char value[]) {
    this.value = Arrays.copyOf(value, value.length);
  }
  
  public int length() {
    return value.length;
  }

  public boolean isEmpty() {
    return value.length == 0;
  }

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

  public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
      char val[] = value;
      for (int i = 0; i < value.length; i++) {
        h = 31 * h + val[i];
      }
      hash = h;
    }
    return h;
  }

  public String toString() {
    return this;
  }
}