Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To test if two objects are identical (that is: whether they're one and the same), use <code>==</code>, not <code>equals()</code>. With the sample input in the question this would print <code>true</code> and <code>false</code>, <em>assuming</em> that you have implemented <code>equals()</code>:</p> <pre><code>System.out.println(obj1.equals(obj2)); // true System.out.println(obj1 == obj2); // false </code></pre> <p>Or perhaps more interesting:</p> <pre><code>Test obj1 = new Test(100, 22); Test obj2 = new Test(100, 22); Test obj3 = obj2; System.out.println(obj1.equals(obj2)); // true System.out.println(obj1 == obj2); // false System.out.println(obj2 == obj3); // true System.out.println(obj1.equals(obj3)); // true </code></pre> <p>Now back to your question. The problem lies in the fact that you haven't properly implemented <code>equals()</code>, which tests for value <em>equality</em> between objects, and that's what you're interested in. For the code in the question, a correct implementation of <code>equals()</code> would look like this:</p> <pre><code>@Override public boolean equals(Object obj) { if (this == obj) // are the objects identical? return true; if (obj == null) // is the other object null? return false; if (getClass() != obj.getClass()) // do the objects have the same class? return false; Test other = (Test) obj; // cast other object if (a != other.a) // is the `a` field equal in both objects? return false; if (b != other.b) // is the `b` field equal in both objects? return false; return true; // ok, the objects are equal :) } </code></pre>
 

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