Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You have to override the <code>equals()</code> method in your class <code>A</code>. By default it uses the implementation inherited from <code>Object</code> class , i.e. <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)" rel="nofollow noreferrer">Object#equals()</a> which compares references, i.e. if both the objects are the same object residing in the heap , it returns <code>true</code> or else <code>false</code>. If you need to check for equality of contents of your objects override the <code>equals()</code> method in your class.</p> <p><strong>Note:</strong> It is generally a good practice to override <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()" rel="nofollow noreferrer">hashCode()</a> while overidding <code>equals()</code>.</p> <p>I have provided a sample implementation :</p> <pre><code>class A { private int value ; A(int value) { this.value = value; } @Override public boolean equals(Object obj) { if(obj==null || !(obj instanceof A)){ return false; } return this.value==((A)obj).value; } @Override public int hashCode() { return this.value; } } </code></pre> <p><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html" rel="nofollow noreferrer">Integer</a> class already overrides this method , <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#equals(java.lang.Object)" rel="nofollow noreferrer">Integer#equals()</a>.</p> <blockquote> <p>Compares this object to the specified object. The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.</p> </blockquote> <p><strong>Suggested Reading:</strong></p> <ol> <li><a href="https://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java">Overriding equals and hashCode in Java</a>.</li> <li><a href="http://books.google.co.in/books?id=ka2VUBqHiWkC&amp;pg=PA45&amp;lpg=PA45&amp;dq=equals+and+hashcode+joshua+bloch&amp;source=bl&amp;ots=yYJkInp-VZ&amp;sig=USfggouMdKPfsM6gR-HV5GatwU0&amp;hl=en&amp;sa=X&amp;ei=RD72UeytLNSBhAeDh4HwCw&amp;ved=0CFYQ6AEwBg#v=onepage&amp;q=equals%20and%20hashcode%20joshua%20bloch&amp;f=false" rel="nofollow noreferrer">Joshua Bloch - always override hashCode when you override equals</a></li> </ol>
 

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