我只是想知道为什么在类的hashCode()方法中使用素数?例如,当使用Eclipse生成我的hashCode()方法时,总会使用素数31:
public int hashCode() {
final int prime = 31;
//...
}
Run Code Online (Sandbox Code Playgroud)
参考文献:
这是关于Hashcode的一篇很好的入门文章和关于我如何找到哈希工作的文章(C#但概念是可转移的): Eric Lippert的GetHashCode指南和规则()
我在hashCode()为我创建的类编写方法时遇到了一些麻烦.此类旨在在TreeSet中使用,因此,它实现了Comparable.该类具有以下变量:
public class Node implements Comparable<Node> {
Matrix matrix;
int[] coordinates= new int[2];
Node father;
int depth;
int cost;
Run Code Online (Sandbox Code Playgroud)
这是该compareTo()方法的实现.我希望TreeSet按成本组织这些Node结构,因此,compareTo()返回简单减法的结果.
public int compareTo(Node nodeToCompare) {
return this.cost - nodeToCompare.cost;
}
Run Code Online (Sandbox Code Playgroud)
我还实现了一种equals()方法.
public boolean equals(Object objectToCompare) {
if(objectToCompare== this) {return true;}
if(objectToCompare== null || objectToCompare.getClass()!= this.getClass()) {return false;}
Node objectNode= (Node) objectToCompare;
return this.father.equals(objectNode.father) &&
this.depth== objectNode.depth &&
this.cost== objectNode.cost &&
this.matrix.equals(objectNode.matrix) &&
Arrays.equals(this.coordinates, objectNode.coordinates);
}
Run Code Online (Sandbox Code Playgroud)
说完这一切之后,我有几个问题:
equals()方法,我应该实现一个新hashCode() …