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

后端 未结 2 1251
忘掉有多难
忘掉有多难 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 12:05

    They allow passing back and forth an array as a backing for routines that are primarily interested in a portions of the array. This allows one to not worry about constructing tons of small arrays, avoiding the costs associated with object construction for particular operations.

    For example, one might use an array as the input buffer, but then need additional arrays to handle the chunked up characters within that buffer, with the triple arguments of array, offset, and count, you can "simulate" reading from the middle of the buffer without the need to create a new (secondary) array.

    This is important, as while you might reasonably want an array (an object in java) to hold the input characters, you probably don't want to allocate and garbage collect thousands of arrays (and copy the characters into them) to pass the data into something that only expects a single word, as delimited by white space (hey, it's just an example).

提交回复
热议问题