j***y 发帖数: 2074 | 1 在The Practice of Programming(中文名:《编程实践》)的第74~75页上看到下面的
代码:
static final int MULTIPLIER = 31; // for hashCodeO
// Prefix hashCode: generate hash from all prefix words
public int hashCode()
{
int h = 0;
for (int i = 0; i < pref.sizeO; i++)
h = MULTIPLIER * h + pref.elementAt(i).hashCodeO;
return h;
}
// Prefix equals: compare two prefixes for equal words
public boolean equals(Object o)
{
Prefix p = (Prefix) o;
for (int i = 0; i < pref.sizeO; i++)
if (!pref.elementAt(i).equals(p.pref.elementAt(i)))
return false;
return true;
}
这两个method里面的pref都是个vector,里面装的是string。这两个method貌似都是递
归函数。
我的问题是,hashCode()和equals()都是class Prefix(见下面的代码)的method,但
从调用方式看,怎么又成了string的成员函数呢?不解啊。
class Prefix {
public Vector pref; // NPREF adjacent words from input
// Prefix constructor: duplicate existing prefix
Prefix(Prefix p)
{
pref = (Vector) p.pref.clone();
}
// Prefix constructor: n copies of str
Prefix(int n, String str)
{
pref = new VectorO;
for (int i = 0; i < n; i++)
pref.addElement(str);
}
//下面应该是hashCode()和equals()的声明
}
请高手答疑,谢了先。 |
r*****l 发帖数: 2859 | 2 equals and hashCode are defined in Object class. Every Java class extends
Object, thus every class has equals and hashCode.
In your example, there is no recursive call.
【在 j***y 的大作中提到】 : 在The Practice of Programming(中文名:《编程实践》)的第74~75页上看到下面的 : 代码: : static final int MULTIPLIER = 31; // for hashCodeO : // Prefix hashCode: generate hash from all prefix words : public int hashCode() : { : int h = 0; : for (int i = 0; i < pref.sizeO; i++) : h = MULTIPLIER * h + pref.elementAt(i).hashCodeO; : return h;
|
x*****p 发帖数: 1707 | 3 Agree with the upper level. |
j***y 发帖数: 2074 | 4 谢谢大家啊,是我搞错了。之前还以为这两个函数都是递归调用呢。 |