天天看点

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。

文章转自庄周梦蝶  ,原文发布时间 2009-01-15