String的长度限制

看String的源码可以得知,String实际存储数据的是char value[],数组的长度是int类型,最大值为231-1= 2147483647
所以String最多存储231-1个字符(注意这里是字符,而不是字节)
但有的同学可能遇到过这样的报错:

而String并没有超过231-1,那这是为什么呢?

关于String的长度限制,这里要分两种情况考虑:

当String为常量时

我们知道,String常量会放入字符串常量池,字符串常量池对字符串的长度做了限制
字符串在class格式文件中的存储格式为:
CONSTANT_Utf8_info {
u1 tag;
u2 length;
u1 bytes[length];
}
u2是无符号的16位整数,最大值为216-1=65535
the class file format spec中也有说明:

The length of field and method names, field and method descriptors, and other constant string values is limited to 65535 characters by the 16-bit unsigned length item of the CONSTANTUtf8info structure (§4.4.7). Note that the limit is on the number of bytes in the encoding and not on the number of encoded characters. UTF-8 encodes some characters using two or three bytes. Thus, strings incorporating multibyte characters are further constrained.

所以String在字符串常量池里的限制为65535个字节(注意这里是字节,而不是字符)
字符与字节的关系与编码有关,这里不讨论

当String为变量时

为变量时,则长度限制为231-1= 2147483647个字符。当然塞不塞的下得看你内存了(。・∀・)ノ

猜你喜欢

转载自www.cnblogs.com/liuwhut/p/12721367.html