Java:String構造器中originalValue.length>size發生的情況

來源:互聯網
上載者:User

最近在看Jdk6中String的源碼的時候發現String的有個這樣的構造方法,原始碼內容如下:

public String(String original) {    int size = original.count;    char[] originalValue = original.value;    char[] v;    if (originalValue.length > size) {            int off = original.offset;            v = Arrays.copyOfRange(originalValue, off, off+size);    } else {        v = originalValue;    }    this.offset = 0;    this.count = size;    this.value = v;    }

這時就對originalValue.length > size這個不解啊。故網上搜尋原因。發現在stackoverflow上有人提到這個問題。還有個國內的文章也說了這個問題。

更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/

1 http://stackoverflow.com/questions/12907986/how-could-originalvalue-length-size-happen-in-the-string-constructor

2  http://www.kankanews.com/ICkengine/archives/99041.shtml

看了上面的兩篇文章的說明,我徹底的明白了。原來是這樣啊。來看看jdk6中String的subString方法。

public String substring(int beginIndex, int endIndex) {    if (beginIndex < 0) {        throw new StringIndexOutOfBoundsException(beginIndex);    }    if (endIndex > count) {        throw new StringIndexOutOfBoundsException(endIndex);    }    if (beginIndex > endIndex) {        throw new StringIndexOutOfBoundsException(endIndex - beginIndex);    }    return ((beginIndex == 0) && (endIndex == count)) ? this :        new String(offset + beginIndex, endIndex - beginIndex, value);    }
// Package private constructor which shares value array for speed.    String(int offset, int count, char value[]) {    this.value = value;    this.offset = offset;    this.count = count;    }

看看上面的源碼,發現使用substring方法後新的String對象的字元數組還是原來對象的字元數組。這樣就出現了originalValue.length > size這個問題。如

String s1="hello world";String s2=s1.substring(6);String s3=new String(s2);

分析上面的代碼 s2的屬性char[] value任然是原來s1的屬性char[] value={'h','e','l','l','o',' ','w','o','r','l','d'}。s2的屬性offset為6,count為5.在new String(s2)時originalValue.length=11>count=5。故我們可知在這樣的情況下會出現本文討論的問題。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.