我在为我创建的类编写hashCode()方法时遇到了一些困难。这个类用于在TreeSet中使用,因此它实现了类似的。该类具有以下变量:
public class Node implements Comparable<Node> {
Matrix matrix;
int[] coordinates= new int[2];
Node father;
int depth;
int cost;下面是compareTo()方法的实现。我希望TreeSet按成本来组织这些节点结构,因此,compareTo()返回一个简单减法的结果。
public int compareTo(Node nodeToCompare) {
return this.cost - nodeToCompare.cost;
}我还实现了一个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);
}说了这些之后,我有几个问题:
equals()方法,我应该实现一个新的hashCode()方法吗?method()?(注意,类型矩阵的变量矩阵有一个implemented)方法hashCode()方法。
就这样!
发布于 2012-03-10 17:03:58
Intellij可以作为一个“右击”功能来实现这一点。只要看它做得正确就能教你很多东西。
在任何情况下你都应该推翻两者。
发布于 2012-03-10 17:14:49
hashCode方法的约定声明,如果两个对象相等,那么调用hashCode()应该会给出相同的整数结果。相反的情况不一定是真,即如果两个hashCodes是相同的,则对象不必相等。
查看您的等于方法(它需要变量转换),您可以添加所有内部成员变量的hashCodes,这些内部成员变量都需要相等,才能使等于方法实现真。例如:
public int hashCode() {
return this.matrix.hashCode() +
this.coordinates[0] +
this.coordinates[1] +
this.father.hashCode() +
this.depth + this.cost;
}以上假设矩阵和父亲永远不是空的,如果不是这样的话,您需要确保检查是否为空。
如果您觉得更冒险,可以用质数乘以上面的几个,以确保不会对不同的数据进行hashCode冲突(如果在hashTables和hashMaps中使用类,这将有助于提高性能)。如果您需要满足空值的需要,则可以这样更好地编写上面的方法:
public int hashCode() {
return ((this.matrix == null) ? 0 : this.matrix.hashCode()) +
17 * this.coordinates[0] +
this.coordinates[1] +
((this.father == null) ? 0 : this.father.hashCode()) +
31 * this.depth + 19 * this.cost;
}发布于 2012-03-10 17:21:23
如果您的集合很小,可以从hashCode方法返回常量。它用来快速找到。hashCodes就像保留元素的框一样。规则如下:
然后返回常量,您将遵守这2条规则,但它会显著降低对不小列表的性能(因为JVM将在所有元素中查找,而不只是在同一个框中的元素中查找)。但返回常数是不好的方法。
PS:对不起,我的写作。英语不是我的母语。
PPS:通常您必须以与等于相同的方式实现hashCode方法(使用相同的元素)。
https://stackoverflow.com/questions/9648305
复制相似问题