Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating a hashCode() Method - Java
    primarykey
    data
    text
    <p>I'm having some trouble writing a <code>hashCode()</code> 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:</p> <pre><code>public class Node implements Comparable&lt;Node&gt; { Matrix matrix; int[] coordinates= new int[2]; Node father; int depth; int cost; </code></pre> <p>Here's the implementation of the <code>compareTo()</code> method. I want the <code>TreeSet</code> to organize these Node structures by their cost, therefore, <code>compareTo()</code> returns the result of a simple subtraction.</p> <pre><code>public int compareTo(Node nodeToCompare) { return this.cost - nodeToCompare.cost; } </code></pre> <p>I also implemented an <code>equals()</code> method.</p> <pre><code>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) &amp;&amp; this.depth== objectNode.depth &amp;&amp; this.cost== objectNode.cost &amp;&amp; this.matrix.equals(objectNode.matrix) &amp;&amp; Arrays.equals(this.coordinates, objectNode.coordinates); } </code></pre> <p>Having said all of that, I have a few questions:</p> <ol> <li>Since I implemented a new <code>equals()</code> method, should I implement a new <code>hashCode()</code> method?</li> <li>How can I go about implementing a new hashCode <code>method()</code> with those variables? (Note that the variable matrix of the type Matrix has a <code>hashCode()</code> method implemented)</li> </ol> <p>That's all!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload