Java字符串的最大長(zhǎng)度
Posted on 2009-01-15 01:37 dennis 閱讀(62524) 評(píng)論(7) 編輯 收藏 所屬分類(lèi): java 、源碼解讀 在cpp中為了可移植性,string的長(zhǎng)度是string::size_type,突然就想知道java允許的最大字符串長(zhǎng)度為多少。看String的源碼:
u2是無(wú)符號(hào)的16位整數(shù),因此理論上允許的string literal的最大長(zhǎng)度是2^16-1=65535。然而實(shí)際測(cè)試表明,允許的最大長(zhǎng)度僅為65534,超過(guò)就編譯錯(cuò)誤了,有興趣可以寫(xiě)段代碼試試,估計(jì)是length還不能為0。
public final class String
110 implements java.io.Serializable, Comparable<String>, CharSequence
111 {
112 /** The value is used for character storage. */
113 private final char value[];
114
115 /** The offset is the first index of the storage that is used. */
116 private final int offset;
117
118 /** The count is the number of characters in the String. */
119 private final int count;
String內(nèi)部是以char數(shù)組的形式存儲(chǔ),數(shù)組的長(zhǎng)度是int類(lèi)型,那么String允許的最大長(zhǎng)度就是Integer.MAX_VALUE了。又由于java中的字符是以16位存儲(chǔ)的,因此大概需要4GB的內(nèi)存才能存儲(chǔ)最大長(zhǎng)度的字符串。不過(guò)這僅僅是對(duì)字符串變量而言,如果是字符串字面量(string literals),如“abc"、"1a2b"之類(lèi)寫(xiě)在代碼中的字符串literals,那么允許的最大長(zhǎng)度取決于字符串在常量池中的存儲(chǔ)大小,也就是字符串在class格式文件中的存儲(chǔ)格式:110 implements java.io.Serializable, Comparable<String>, CharSequence
111 {
112 /** The value is used for character storage. */
113 private final char value[];
114
115 /** The offset is the first index of the storage that is used. */
116 private final int offset;
117
118 /** The count is the number of characters in the String. */
119 private final int count;
CONSTANT_Utf8_info {
u1 tag;
u2 length;
u1 bytes[length];
}
u1 tag;
u2 length;
u1 bytes[length];
}
u2是無(wú)符號(hào)的16位整數(shù),因此理論上允許的string literal的最大長(zhǎng)度是2^16-1=65535。然而實(shí)際測(cè)試表明,允許的最大長(zhǎng)度僅為65534,超過(guò)就編譯錯(cuò)誤了,有興趣可以寫(xiě)段代碼試試,估計(jì)是length還不能為0。