String源碼分析,string源碼

來源:互聯網
上載者:User

String源碼分析,string源碼

String類內部維護了一個char[]類型的value用來儲存字串,相對來說源碼較為簡單些。

1.不可變性

String的不可變主要體現在三個方面:

  • String類被定義為final類型,不可被繼承
  • String中的value[]被定義為final
  • String中的所有產生新的String的操作底層都調用Array.copy或者System.copy來產生一個新的String對象
2.建構函式,String的建構函式較為簡單,但以下幾個較為特殊
    public String(String original) {        this.value = original.value;        this.hash = original.hash;    }        String(char[] value, boolean share) {        // assert share : "unshared not supported";        this.value = value;    }

以上兩個是較為特殊的一類建構函式,第一個用一個現成的String來初始化一個新的String對象,構造方法直接將新的String對象的value指向老的value對象。由於String是不可變的,所以這裡不需要重新copy一份value的對象。第二個構造方法看似會破壞String類型的不可變性(當參數value變化時String也會變化),但該構造方法並沒有聲明為public,只允許在包內使用,被聲明為public的String(char value[])底層調用的是Array.copy來實現底層資料拷貝的,上述的兩個建構函式已經不建議使用

    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.value = Arrays.copyOfRange(value, offset, offset+count);    }

上面這個建構函式較為典型,很多其他的建構函式都與其類似或者底層調用了該建構函式,入參是一個char數組(byte[]),offset位移位置及count位移量。底層調用Arrays.copy函數來進行深度複製。

    public String(StringBuffer buffer) {        synchronized(buffer) {  //保證安全執行緒            this.value = Arrays.copyOf(buffer.getValue(), buffer.length());        }    }        public String(StringBuilder builder) {        this.value = Arrays.copyOf(builder.getValue(), builder.length());    }

上述兩個建構函式入參分別是StringBuffer和StringBuilder,底層都是調用Arrays.copyOf,唯一不同的是StringBuffer是安全執行緒的,所有調用時需要用synchronized關鍵字。

3.其他方法
    static int indexOf(char[] source, int sourceOffset, int sourceCount,            char[] target, int targetOffset, int targetCount,            int fromIndex) {        if (fromIndex >= sourceCount) {            return (targetCount == 0 ? sourceCount : -1);        }        if (fromIndex < 0) {            fromIndex = 0;        }        if (targetCount == 0) {            return fromIndex;        }        char first = target[targetOffset];        int max = sourceOffset + (sourceCount - targetCount);        for (int i = sourceOffset + fromIndex; i <= max; i++) {            /* Look for first character. */            if (source[i] != first) {                while (++i <= max && source[i] != first);            }            /* Found first character, now look at the rest of v2 */            if (i <= max) {                int j = i + 1;                int end = j + targetCount - 1;                for (int k = targetOffset + 1; j < end && source[j]                        == target[k]; j++, k++);                if (j == end) {                    /* Found whole string. */                    return i - sourceOffset;                }            }        }        return -1;    }        static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,            char[] target, int targetOffset, int targetCount,            int fromIndex) {        /*         * Check arguments; return immediately where possible. For         * consistency, don't check for null str.         */        int rightIndex = sourceCount - targetCount;        if (fromIndex < 0) {            return -1;        }        if (fromIndex > rightIndex) {            fromIndex = rightIndex;        }        /* Empty string always matches. */        if (targetCount == 0) {            return fromIndex;        }        int strLastIndex = targetOffset + targetCount - 1;        char strLastChar = target[strLastIndex];        int min = sourceOffset + targetCount - 1;        int i = min + fromIndex;        startSearchForLastChar:        while (true) {            while (i >= min && source[i] != strLastChar) {                i--;            }            if (i < min) {                return -1;            }            int j = i - 1;            int start = j - (targetCount - 1);            int k = strLastIndex - 1;            while (j > start) {                if (source[j--] != target[k--]) {                    i--;                    continue startSearchForLastChar;                }            }            return start - sourceOffset + 1;        }    }

indexOf和lastIndexOf主要是index和lastIndex函數的底層調用,通讀代碼會發現底層實現並沒有特別牛逼的kmp演算法,仍然是一個字元一個字元掃描實現的。其中lastIndexOf還是用了continue startSearchForLastChar;相對來說比較少見。

    public String replace(char oldChar, char newChar) {        if (oldChar != newChar) {            int len = value.length;            int i = -1;            char[] val = value; /* avoid getfield opcode */            while (++i < len) {                if (val[i] == oldChar) {                    break;                }            }            //如果找不到則返回this            if (i < len) {                char buf[] = new char[len];                for (int j = 0; j < i; j++) {                    buf[j] = val[j];                }                while (i < len) {                    char c = val[i]; //替換                    buf[i] = (c == oldChar) ? newChar : c;                    i++;                }                //返回新的String,利用上述包內的非public建構函式                return new String(buf, true);            }        }        return this;    }

replace用於將String對象中的一個字元替換為另一個字元,如果找不到制定的字元則返回本身,如果找到則會另建一個新的String對象返回。

---恢複內容結束---

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.