博士后(mechanics of materials/biomechanics/mechanobiology)# Engineering - 工程
j*y
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()的声明
}
请高手答疑,谢了先。
代码:
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()的声明
}
请高手答疑,谢了先。