Java字符串的最大长度
2023-03-14 10:25:57 时间
在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格式文件中的存储格式: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;
CONSTANT_Utf8_info {
u1 tag;
u2 length;
u1 bytes[length];
}
u1 tag;
u2 length;
u1 bytes[length];
}
u2是无符号的16位整数,因此理论上允许的string literal的最大长度是2^16-1=65535。然而实际测试表明,允许的最大长度仅为65534,超过就编译错误了,有兴趣可以写段代码试试,估计是length还不能为0。
文章转自庄周梦蝶 ,原文发布时间 2009-01-15
相关文章
- 详解Java Stream的分组和聚合
- Java底层知识:什么是 “桥接方法” ?
- 一篇带给你如何写好一个Java类?
- Java 中如何加密配置文件中的数据库账号和密码?
- G1 面向服务端(多CPU)应用的垃圾回收器
- JDK动态代理为什么必须要基于接口?
- 聊聊Java NIO Selector 使用
- Spring Security的内置过滤器是如何维护的
- 浅析Java语言中接口的特点和继承相关知识
- 如何规划你的Java开发人员职业道路
- Spring Cloud Sleuth 和 Zipkin 进行分布式跟踪使用指南
- 预测2022 年 Java 未来的五种技术趋势
- JDK、JRE 和 JVM 有什么用,它们是怎样运行的
- Java不支持协程?那是你不知道Quasar!
- 之前被问的 ConcurrentHashMap 面试题,我汇总一下!
- 你知道JDK、JRE与JVM的区别吗?我来告诉你
- Java那些事-聊聊那些易混淆的概念:OpenJDK/oracleJDK,Java EE/Jakarta EE
- 学习 Java 中最困难的部分以及如何克服它们
- 用于微服务和云原生开发的六大 Java 框架
- Spring事务失效场景汇总