I know there are other questions about the general best practices while over riding hashCode and equals, but I have a very specific question.
I have a class that has as an instance variable, an array of the same class. To be more explicit, here's the code:
Class Node{
Node arr[] = new Node[5];
}
I need to overwrite hashCode for the class Node, and the array is an important, deciding factor in determining whether two Nodes are the same. How can I incorporate the array into the calculation of hashCode effectively?
--Edit--
I'm trying to check if the two nodes are the same, meaning that they have the same number of children, and that those children lead to the exact same states. Therefore, I'm effectively trying to compare the subtrees at the two node. I'm wondering if I can use hashing to do this equality check.
I think I actually need to hash the entire subtree, but I'm not sure how I'd go about doing that given the recursive nature of my class definition.
So all java classes have the hashcode() method by default. We can override these methods in our classes. Hashcode() is a method to return an unique integer which is used for indentifying the bucket where this object will be stored for hashing based collections like HashMap.
if you override equals, you must override hashCode. hashCode must generate equal values for equal objects. equals and hashCode must depend on the same set of significant fields . You must use the same set of fields in both of these methods.
Include http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#hashCode(java.lang.Object[]) as part of the hashCode() implementation.
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