String的最大长度

来源:互联网 发布:梨园有个淘宝城 编辑:程序博客网 时间:2024/05/18 01:30

Java字符串的最大长度
Posted on 2009-01-15 01:37 dennis 阅读(40313) 评论(5) 编辑 收藏 所属分类: java 、源码解读
在cpp中为了可移植性,string的长度是string::size_type,突然就想知道java允许的最大字符串长度为多少。看String的源码:
public final class String
implements java.io.Serializable, Comparable, CharSequence
{
/* The value is used for character storage. /
private final char value[];
/* The offset is the first index of the storage that is used. /
private final int offset;

   /** The count is the number of characters in the String. */    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。

总结 : String在Java中最大长度为65534

来源:http://www.blogjava.net/killme2008/archive/2009/01/15/251368.html

0 0