Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding hashCode in Java for a specific case

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.

like image 750
efficiencyIsBliss Avatar asked May 04 '11 17:05

efficiencyIsBliss


People also ask

Can we override hashCode method in Java?

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.

Can we override hashCode method How?

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.


1 Answers

Include http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#hashCode(java.lang.Object[]) as part of the hashCode() implementation.

like image 106
Joseph Ottinger Avatar answered Sep 28 '22 03:09

Joseph Ottinger