说 Java 字符串对象本质上是一个定义为不可变字符数组的类是否准确?
不,Java String 对象是(目前 - 这是我收集的可能正在更改的实现细节)一个包含几个字段的类:
- A
char[]
包含实际字符
- 数组的起始索引
- 一个长度
- 一个缓存的哈希码,延迟计算
索引和长度的原因是几个字符串可以包含对相同的引用char[]
。这被一些操作使用,例如substring
(在许多实现中,无论如何)。
The important thing is the API for String
though - which is very different to the API for an array. It's the API you would think of when you take the JLS definition into account: a String
represents a sequence of Unicode code points. So you can take a subsequence (Substring
), find a given subsequence (indexOf
), convert it to an upper case sequence etc.
In fact the JLS would be slightly more accurate to call it a sequence of UTF-16 code units; it's entirely possible to construct a string which isn't a valid sequence of Unicode code points, e.g. by including one half of a "surrogate pair" of UTF-16 code units but not the other. There are parts of the API which do deal with the String
in terms of code units, but frankly most developers spend most of the time treating strings as if non-BMP characters didn't exist.