【发布时间】:2014-08-04 03:01:51
【问题描述】:
我查看了String.hashcode() 方法的源代码。这是6-b14 中的实现,已经改变了。
public int hashCode() {
int h = hash;
if (h == 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;
}
我的问题是关于这一行的:
int len = count;
其中count 是一个全局变量,表示字符串的字符数。
为什么这里使用局部变量len 表示循环条件而不是全局变量本身?因为没有变量的操作,只有读取。如果全局字段用于读取或写入它,那么使用局部变量是否只是一种好习惯?如果答案是肯定的,为什么还要阅读?
【问题讨论】:
-
您使用的是什么版本的 Java?
-
这是
6b-14。这是问题.. :) -
s/global/instance/g -
也许在这种情况下纯粹是为了可读性?
count听起来模棱两可,len几乎总是表示数组或字符串的长度。 -
@MDeSchaepmeester 对我来说,仅仅因为一个更好的名字就使用一个额外的变量听起来不对。
标签: java string global-variables local-variables