我有一个实现了hashCode()的vector类.它不是由我编写的,而是使用2个素数来乘以2个向量分量,然后对它们进行异或运算.这里是:
/*class Vector2f*/
...
public int hashCode()
{
return 997 * ((int)x) ^ 991 * ((int)y); //large primes!
}
Run Code Online (Sandbox Code Playgroud)
...因为这是来自一个已建立的Java库,我知道它的工作正常.
然后我有一个Boundary类,它包含2个向量,"start"和"end"(表示一行的端点).这两个向量的值是边界的特征.
/*class Boundary*/
...
public int hashCode()
{
return 1013 * (start.hashCode()) ^ 1009 * (end.hashCode());
}
Run Code Online (Sandbox Code Playgroud)
在这里,我试图为构成这个边界的唯一2元组向量(开始和结束)创建一个好的hashCode().我的问题:这个hashCode()实现是否有效?
(请注意,我在后一个hashCode()实现中使用了2个不同的素数;我不知道这是否有必要但是为了安全而不是为了避免常见因素更好,我猜 - 因为我认为这是为什么素数在散列函数中很受欢迎.)
我不明白一个集合如何确定两个对象何时相等.更具体地说,add一个集合的方法何时真正添加一个新对象,何时它不是一个新对象,因为该对象已经在集合中?
例如,我有以下类中的对象:
class Action {
final Function function;
final String description;
Action(this.function, this.description);
call() => function();
toString() => description;
}
Run Code Online (Sandbox Code Playgroud)
现在我认为以下集合将包含2个元素,因为其中2个是相等的:
void main() {
Set<Action> actions = new Set()
..add(new Action(() => print("a"), "print a"))
..add(new Action(() => print("a"), "print a"))
..add(new Action(() => print("b"), "print b"));
}
Run Code Online (Sandbox Code Playgroud)
但相反,这个集合包含3个Action对象.看演示.如何确保在集合中看到相等的对象相等?