Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First, in that line, you need to change <code>Hashvalue</code> to <code>HashValue</code>, since your class is actually called <code>HashValue</code>.</p> <p>Then, uncommenting the line gives you this:</p> <pre><code>public boolean equals(Object oo) { if(oo instanceof HashValue) HashValue hh = (HashValue)oo; if (this.x==hh.x) { return true; } else { return false; } } </code></pre> <p>There are a few things wrong with this:</p> <ol> <li><p>This doesn't compile because <code>hh</code> isn't in scope when you end up using it.</p></li> <li><p>The first if statement should either make sure that the function doesn't run at all when you compare two things that aren't HashValues (i.e. throw an exception), or it should return <code>false</code> because HashValues are never equal to other types of objects. I generally prefer returning <code>false</code> to throwing an exception.</p></li> <li><p>The second if statement is redundant, because you're just returning what the condition evaluates to.</p></li> </ol> <p>Rework your method like this:</p> <pre><code>public boolean equals(Object oo) { if(!(oo instanceof Hashvalue)) { return false; } HashValue hh = (HashValue)oo; return (this.x == hh.x); } </code></pre> <p>This isn't quite right, either. To make sure that all equal objects have the same hash code, you have to override <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#hashCode()" rel="nofollow noreferrer"><code>hashCode()</code></a> in <code>HashValue</code>, and <strong>you</strong> must make sure that it lives up to the guarantee. Here, you could just add this:</p> <pre><code>// inside HashValue int hashCode() { return x; } </code></pre> <p>The implementation is trivial because your object is just a wrapper around an <code>int</code>. You'll need to think harder about this as your objects get more sophisticated.</p>
 

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