2

以下是 for 的hashCode()来源String

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;
}

off被初始化offset为 0(我在源代码中到处查看,每个赋值都将其设为 0,仅此而已)。然后在for循环中,val通过 viaoff而不是i. 为什么是这样?为什么不直接使用i并消除对offset开始的需要?我认为存在是有充分理由的offset。有什么见解吗?

4

3 回答 3

7

substring 函数创建一个新的 String,它的 offset 值不是 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);
}

调用此构造函数。

// Package private constructor which shares value array for speed.
String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}

所以偏移量并不总是0。

于 2013-06-28T04:45:09.140 回答
5

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

于 2013-06-28T04:42:30.303 回答
2

offset 和 count 在旧版本中用于子字符串 char 数组共享。在当前版本中不再使用共享,这些字段已被删除。请参阅 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;
}
于 2013-06-28T04:53:52.197 回答