Why is String class in java implemented using char[], offset and length?

后端 未结 2 1250
忘掉有多难
忘掉有多难 2021-01-29 11:34

Why does String class in java have char[] value, int offset and int count fields. What is their purpose and what task do they accomplish?<

2条回答
  •  不思量自难忘°
    2021-01-29 11:50

    The char[] array holds the array of characters making up that string.

    The offset and count are used for the String.substring() operation. When you take a substring of a string the resultant String references the original character array, but stores an associated offset and length (this is known as a flyweight pattern and is a commonly used technique to save memory)

    e.g. String.substring("ABCDEF", 1, 2);

    would reference the original array of A,B,C,D,E,F but set offset to 1 and length to 1 (since the substring method uses start and end indices). Note you can do this trivially since the character array is immutable. You can't change it.

    Note: This has changed recently (7u6, I believe) and is no longer true in recent versions. I suspect this is due to the realisation that this optimisation isn't really used much.

提交回复
热议问题