为什么Java String实现中存在偏移量? [英] Why is there an offset in the Java String implementation?

查看:248
本文介绍了为什么Java String实现中存在偏移量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究实现,但我不明白为什么会有偏移.我认为这很重要.

I've been looking at the implementation and I don't understand why there is an offset. I assume it is important.

我正在参加由Sedgewick教授的算法课程,现在我们正在谈论字符串.在演讲中,他简要地讨论了String的实现,但是他没有讲解为什么会有偏移(请注意,如果演讲不在网上,我肯定会问的).

I'm taking an Algorithms course taught by Sedgewick, and we're talking about Strings now. In lecture he briefly discussed the String implementation, but he doesn't go over why there is an offset (Note, if lectures were not online, I would definitely have asked).

似乎在实现中创建一个String时,它会得到一个偏移量,而我似乎无法理解为什么需要一个.即使出于子字符串的目的,我也不太明白为什么会有偏移量.例如,显然,如果您创建字符串"David",则它实际上是['X', 'X', 'D', 'a', 'v', 'i', 'd', 'X']或具有类似性质的字符串,其中它会被'X'偏移.为什么会这样?

It seems when one makes a String that within the implementation, it is given an offset, and I can't seem to understand why one is needed. Even for substring purposes I don't quite follow why you would have an offset. For example, apparently if you create a string "David", it is really ['X', 'X', 'D', 'a', 'v', 'i', 'd', 'X'], or something of that nature, where it is offset by the 'X's. Why is this?

推荐答案

在需要从另一个更长的字符串(类似于substring())派生字符串的情况下,这很有用.

This can be useful in cases where strings need to be derived from another longer string, akin to substring().

在这种情况下,可以在调整偏移量和长度的同时使用相同的(不可变的)支持数组,以节省内存并优化性能.

In this case the same (immutable) backing array may be used, while adjusting the offset and length, to save memory and optimize performance.

在JDK7中不再是这种情况.

This is no longer the case in JDK7.

这篇关于为什么Java String实现中存在偏移量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆