java.lang.String 中的偏移量有什么用?

What does offset in java.lang.String holds?

在java的字符串class中,有一个变量定义如下:

private final int offset;

这个偏移量有什么意义?

形成source code:

The offset is the first index of the storage that is used.

来自变量偏移量的注释:

The offset is the first index of the storage that is used.

在内部,String 表示为数组字符序列

这是数组中要使用的第一个字符。

引入它是因为某些操作,如 substring 使用不同的偏移量 使用 原始字符数组创建新的 String

所以基本上是为子字符串操作的性能调整引入的变量。

注意: offset 变量总是与变量 private final int count;

来自String.java

The offset is the first index of the storage that is used.

/** The value is used for character storage. */
private final char value[];

/** The offset is the first index of the storage that is used. */    
private final int offset;

您可以看到它被用于各种方法,例如:

public char charAt(int index) {
    // ...
    return value[index + offset];
}