1. 程式人生 > >原始碼閱讀筆記1 --- String

原始碼閱讀筆記1 --- String

    //此處final表示String類不可以被繼承
public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    //value這個字元陣列被用於字元儲存,用private修飾並且沒有set方法(沒有提供可變的介面),說明陣列不可變,數組裡的內容也不可以變
    private final char value[];

    public String() {
        this.value = "".value;
    }

    public
String(String original) { this.value = original.value; this.hash = original.hash; } //也可以傳字元陣列,將傳進來的字元陣列copy到value陣列中 public String(char value[]) { this.value = Arrays.copyOf(value, value.length); } public String(char value[], int offset, int count) { if
(offset < 0) { throw new StringIndexOutOfBoundsException(offset); } if (count <= 0) { if (count < 0) { throw new StringIndexOutOfBoundsException(count); } if (offset <= value.length) { this.value
= "".value; return; } } // Note: offset or count might be near -1>>>1. if (offset > value.length - count) { throw new StringIndexOutOfBoundsException(offset + count); } this.value = Arrays.copyOfRange(value, offset, offset+count); } //返回value陣列中下標為index的字元,若是越界的話就丟擲一個異常 public char charAt(int index) { if ((index < 0) || (index >= value.length)) { throw new StringIndexOutOfBoundsException(index); } return value[index]; } //String類重寫Object類中的equal方法,父類引用指向子類物件 public boolean equals(Object anObject) { if (this == anObject) { return true; } //instanceof 運算子是用來在執行時指出物件是否是特定類的一個例項 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 boolean equalsIgnoreCase(String anotherString) { return (this == anotherString) ? true : (anotherString != null) && (anotherString.value.length == value.length) && regionMatches(true, 0, anotherString, 0, value.length); } //返回字元ch對應的下標 public int indexOf(int ch) { return indexOf(ch, 0); } public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > value.length) { throw new StringIndexOutOfBoundsException(endIndex); } int subLen = endIndex - beginIndex; if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } return ((beginIndex == 0) && (endIndex == value.length)) ? this : new String(value, beginIndex, subLen); } public String trim() { int len = value.length; int st = 0; char[] val = value; /* avoid getfield opcode */ while ((st < len) && (val[st] <= ' ')) { st++; } while ((st < len) && (val[len - 1] <= ' ')) { len--; } return ((st > 0) || (len < value.length)) ? substring(st, len) : this; } }