1. 程式人生 > >Java字串的最大長度

Java字串的最大長度

在cpp中為了可移植性,string的長度是string::size_type,突然就想知道java允許的最大字串長度為多少。看String的原始碼:

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內部是以char陣列的形式儲存,陣列的長度是int型別,那麼String允許的最大長度就是Integer.MAX_VALUE了。又由於java中的字元是以16位儲存的,因此大概需要4GB的記憶體才能儲存最大長度的字串。不過這僅僅是對字串變數而言,如果是字串字面量(string literals),如“abc"、"1a2b"之類寫在程式碼中的字串literals,那麼允許的最大長度取決於字串在常量池中的儲存大小,也就是字串在class格式檔案中的儲存格式:

CONSTANT_Utf8_info {
        u1 tag;
        u2 length;
        u1 bytes[length];
}


    u2是無符號的16位整數,因此理論上允許的string literal的最大長度是2^16=65536。然而實際測試表明,允許的最大長度僅為65534,超過就編譯錯誤了,有興趣可以寫段程式碼試試。