I'm having some trouble writing a hashCode()
method for a class I created. This class is meant to be used inside a TreeSet, and as such, it implements Comparable. The class has the following variables:
public class Node implements Comparable<Node> {
Matrix matrix;
int[] coordinates= new int[2];
Node father;
int depth;
int cost;
Here's the implementation of the compareTo()
method. I want the TreeSet
to organize these Node structures by their cost, therefore, compareTo()
returns the result of a simple subtraction.
public int compareTo(Node nodeToCompare) {
return this.cost - nodeToCompare.cost;
}
I also implemented an equals()
method.
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);
}
Having said all of that, I have a few questions:
equals()
method, should I implement a new hashCode()
method?method()
with those variables? (Note that the variable matrix of the type Matrix has a hashCode()
method implemented)That's all!
ADVERTISEMENT. The hashCode() is a method of Java Integer Class which determines the hash code for a given Integer. It overrides hashCode in class Object. By default, this method returns a random integer that is unique for each instance.
In this program, after getting a list of Method objects of a class object by calling getMethods() method of class object, hashCode() method of Method object is called for each method object of the list. At last, the hashcode is printed along with the method name.
Your compareTo
method is not consistent with your equals
method: your compareTo
method says that two instances are equivalent if they have the same cost
— such that a TreeSet
can only ever contain at most one instance with a given cost
— but your equals
method says that they're only equivalent if they have the same cost
and are the same in various other ways.
So, assuming that your equals
method is correct:
compareTo
method to be consistent with it.hashCode
method that is consistent with it. I recommend using the same sort of logic as is used by java.util.List.hashCode()
, which is a straightforward and effective way to assemble the hash-codes of component objects in a specific order; basically you would write something like: 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With