Gon*_*nço 18 java hash hashcode
我在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()方法吗?method()使用这些变量实现新的hashCode ?(注意,Matrix类型的变量矩阵有一个hashCode()实现的方法)就这样!
rua*_*akh 22
你的compareTo方法是不是与你一致的equals方法:你的compareTo方法说,两个实例是等价的,如果他们有相同的cost-这样一个TreeSet永远只能包含最多一个实例与给定的cost-但你的equals方法说,他们只相当于如果他们具有相同cost 并且以各种其他方式相同.
所以,假设你的equals方法是正确的:
compareTo方法以保持一致.hashCode与之一致的方法.我建议使用与之相同的逻辑java.util.List.hashCode(),这是一种直接有效的方式来按特定顺序组装组件对象的哈希码; 基本上你会写一些像:int hashCode = 1; hashCode = 31 * hashCode + (father == null ? 0 : father.hashCode()); hashCode = 31 * hashCode + depth; hashCode = 31 * hashCode + cost; hashCode = 31 * hashCode + matrix.hashCode(); hashCode = 31 * hashCode + java.util.Arrays.hashCode(coordinates); return hashCode;
| 归档时间: |
|
| 查看次数: |
29250 次 |
| 最近记录: |