JDK源碼-String

String這個類是將String 放入到char數組來實現功能的。 首先看一下三個全局變量

1.offset(偏移量) : 默認爲0 
2. count(大小) : count爲當前字符串轉爲char之後的數組長度。 arrayOfchar.Length 
3. value(char數組): arrayOfchar

方法一: isEmpty() 
源碼:

public boolean isEmpty() {
    return count == 0;
}

很簡單 isEmpty等價於array.length() == 0。 
所以說 準確的判斷字符串相等 : Str != null && !Str.isEmpty() 。 
isEmpty應該是在所有字符串判斷效率最高的 1.isEmpty 2.”“.equals() 3. str.length <= 0


方法二:equals() 
源碼:

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

第一步判斷是否爲同一個對象,如果是則直接返回true。 
第二步通過instanceof 來判斷是否爲String類型,如果不是直接返回false。 
第三步判斷長度。 
第四步將String轉成char數組之後,一個字符一個字符進行比較,如果有一個不相等,則返回false。


方法三:compareTo() 
源碼:

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

原理與equals相同,都是通過數組來實現,但是邏輯不同。我沒有找到可以改變偏移位的方法,不知道else有什麼用,不過既然寫了,肯定有用,存在皆有道理嘛。它是取相同偏移位的進行逐個比較。如果不同則相減,就會出現正負數了。如果全部相等就是0。


方法四:startsWith()和endsWith() 
這兩個方法在源碼中實際上是調用的同一個方法。 
源碼:

public boolean startsWith(String prefix) {
    return startsWith(prefix, 0);
}
public boolean endsWith(String suffix) {
    return startsWith(suffix, count - suffix.count);
}
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;
}

第二個參數是說要從哪個下邊開始進行比較,沒有這個參數時默認爲0,endwith是從當前數組長度-指定字符長度開始進行比較。不相同就返回false

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章