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-1=65535。然而实际测试表明,允许的最大长度仅为65534,超过就编译错误了,有兴趣可以写段代码试试,估计是length还不能为0。

posted @ 2015-08-19 15:08  牧之丨  阅读(4101)  评论(0编辑  收藏  举报