Comments (3)
浅层
通过阅读 String 类的源码,知道有这样的成员变量:
private final int count;
其中,注释也说的比较清楚:
count 用来记录字符串的长度,是 int 型,则 String 的最大长度为 Integer.MAX_VALUE
,即 2 的 31 次方。
from myrecord.
深层
《深入理解java虚拟机》中讲到 Class 文件结构。得知在编译为字节码文件后,String 类型的变量的值在常量池中使用 CONSTANT_utf8-info
类型表示,而 CONSTANT_utf8-info
型常量的结构为 u1u2u1 :
CONSTANT_Utf8_info {
u1 tag;
u2 length;
u1 bytes[length];
}
u2 是无符号的 16 位整数,因此理论上允许的 string literal 的最大长度是 2^16-1=65535。
然而实际测试表明,允许的最大长度仅为 65534,超过就编译错误了~~
原因分析:
在 class 文件的规范中, CONSTANT_Utf8_info 表中使用一个 16 位的无符号整数来记录字符串的长度的,最多能表示 65535 个字节,而 java class 文件是使用一种变体 UTF-8 格式来存放字符的,null 值使用两个字节来表示,因此只剩下 65534个字节。
也正是变体 UTF-8 的原因,如果字符串中含有中文等非 ASCII 字符,那么双引号中字符的数量会更少(一个中文字符占用三个字节)。
from myrecord.
补充
65534 只是在编译阶段的限制,字面量形式一般存储在常量池(如上分析 16 位),运行中时,String 对象的内部字符数组可以通过其它手段拼接成大于65534 长度的字符串。
存在堆中,也不绝对是;但是运行时在本地方法只存储该对象的引用,即 reference 类型,该类型可能是 4 个字节,也可能是 8 个字节。所以理论值是 2^32 或者 2^64 。
所以运行时的字符串长度最多还应该是 Integer.MAX_VALUE
,2^32 也就是 4G。
from myrecord.
Related Issues (20)
- MySQL中避免重复插入的方法
- 不同系统的换行问题
- MD5与SHA HOT 3
- 在线工具收集 HOT 3
- 关于Git配置 HOT 2
- Tips HOT 6
- javaagent(Java探针技术)
- Vue常见使用中的问题 HOT 2
- 关于MySQL中字段的长度 HOT 2
- JS生态相关
- require和import
- 现代开发模式魔法研究 HOT 1
- Github的CI/CD工具
- 关于防抖(debounce)函数
- Docker Compose 相关 HOT 2
- 关于微信机器人调研 HOT 2
- CentOS 8 停止支持,如何选择替代? HOT 3
- Web前端开发环境相关 HOT 1
- SpringMVC中使用PathVariable遇到特殊字符问题 HOT 1
- 你好 po主 java深似海的课程可以分享下吗 可有偿
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from myrecord.