复制value
参考到val
变量的目的是什么,反对直接使用它?为什么在String#hashCode中有一个局部变量引用值数组?
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value; // private final char value[];
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
不清楚,但成员变量仍然通过'value.length'使用。 –
@AndyTurner,但这就是答案,对吧?如果在执行'hashCode'过程中'value'发生了变化,您可能会得到一个'ArrayIndexOutOfBoundsException'或者简单地计算一个错误的哈希码。 – aioobe
@aioobe执行过程中'private final char [] value'是如何改变的,通过检查它的长度来检测?你真的期望'val'的元素可以改变,'String'是不可变的吗? –