在String的hashCode()中,偏移存在的原因是什么?似乎多余

Ste*_* P. 2 java

以下是hashCode()for 的来源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;
}
Run Code Online (Sandbox Code Playgroud)

off被初始化为offset,为0(我查看了源中的每个位置,每个赋值都为0,这就是全部).然后在for循环中,val迭代通过via off而不是i.为什么是这样?为什么不直接使用i和消除offset开始的需要?我认为存在一个很好的理由offset.任何见解?

Ren*_*Ren 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);
}
Run Code Online (Sandbox Code Playgroud)

调用此构造函数.

// 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;
}
Run Code Online (Sandbox Code Playgroud)

所以偏移量并不总是0.


Pat*_*shu 5

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