在 Java 中,String
对象的最大大小是多少,引用 length()
方法调用?
我知道 length()
将 String
的大小返回为 char []
;
最佳答案
考虑到 String
类的 length
方法返回 int
,该方法返回的最大长度为 Integer.MAX_VALUE
,即 2^31 - 1
(或大约 20 亿。)
在数组的长度和索引方面,(如char[]
,这可能是String
s内部数据表示的实现方式),Chapter 10: Arrays The Java Language Specification, Java SE 7 Edition 的内容如下:
The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the components of the array. If an array has
n
components, we sayn
is the length of the array; the components of the array are referenced using integer indices from0
ton - 1
, inclusive.
此外,索引必须是 int
值,如 Section 10.4 中所述:
Arrays must be indexed by
int
values;
因此,限制似乎确实是 2^31 - 1
,因为这是非负 int
值的最大值。
但是,可能会有其他限制,例如数组的最大可分配大小。
关于java - Java中字符串的最大长度-调用length()方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/816142/