Java 在字符串的hashCode()中,什么';是偏移量'的原因;谁的存在?似乎多余

Java 在字符串的hashCode()中,什么';是偏移量'的原因;谁的存在?似乎多余,java,Java,下面是String的hashCode()的源代码: public int hashCode() { int h = hash; if (h == 0 && count > 0) { int off = offset; char val[] = value; int len = count; for (int i = 0; i < len; i++) {

下面是
String
hashCode()
的源代码:

public int hashCode() 
{
   int h = hash;

   if (h == 0 && count > 0) 
   {
        int off = offset;
        char val[] = value;
        int len = count;

        for (int i = 0; i < len; i++) 
        {
            h = 31*h + val[off++];
        }

        hash = h;
   }

   return h;
}
public int hashCode()
{
int h=散列;
如果(h==0&&count>0)
{
int off=偏移量;
char val[]=值;
int len=计数;
对于(int i=0;i

off
被初始化为
offset
,它是0(我在源代码中到处寻找,每个赋值都是0,仅此而已)。然后在
for
循环中,通过
off
而不是
i
迭代
val
。为什么会这样?为什么不直接使用
i
并从一开始就不需要
offset
?我认为存在
offset
是有充分理由的。有什么见解吗?

在Java中,可以将字符串定义为父字符串的子字符串,以便在为一个巨大字符串创建多个子字符串(例如解析它)时节省空间。在这种情况下,它们使用偏移量来确定它们在父字符串中的起始位置。

子字符串函数创建一个新字符串,该字符串的偏移量值不是0

public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
    throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
    throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
    throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
    new String(offset + beginIndex, endIndex - beginIndex, value);
}

所以偏移量并不总是0。

在旧版本中,偏移量和计数用于子字符串字符数组共享。在当前版本中,不再使用共享,这些字段已被删除。请参阅1.7.0_15中的hashCode impl

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}
public int hashCode(){
int h=散列;
如果(h==0&&value.length>0){
char val[]=值;
for(int i=0;i
如果它是另一个已在内存中的大字符串的子字符串,该怎么办?“我认为存在偏移量是有充分理由的。有什么见解吗?”请阅读
子字符串
方法的代码!!下面是
String
hashCode()
的源代码,它属于OpenJDK,可能也属于HotSpot。请注意,不同的JVM实现可能会有不同的
hashCode
方法
String
类的实现,例如JRockit。完全没有做到这一点。谢谢
public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}