以下是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.任何见解?
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.