Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For that you need to override <code>equals()</code> method for class <code>A</code> If you do not override the method it will use the <code>Object</code> class equals method which checks whether the reference varaibles refer to the same object or not. </p> <p>With <code>Integer</code> class, the <code>equals()</code> method is already overridden and which checks for the value. </p> <p>Also, whenever you are overriding <code>equals()</code>, override <code>hashcode()</code> also</p> <pre><code>public class A { private int number; A(int number){ this.number = number; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + number; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; A other = (A) obj; if (number != other.number) return false; return true; } public static void main(String[] args) { A a1 = new A(5); A a2 = new A(5); System.out.println(a1.equals(a2)); } } </code></pre> <p>This prints out <code>true</code>.</p> <blockquote> <p>Why? Can anyone explain?</p> </blockquote> <p>With <code>Integer</code> class, the <code>equals()</code> method is already overridden and which checks for the value. </p> <p><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#equals%28java.lang.Object%29" rel="nofollow">Integer#equals()</a></p> <p>A good tutorial helping understand the significance of equals method is provided on <a href="http://www.thejavageek.com/2013/06/26/what-is-the-significance-of-equals-method-in-java/" rel="nofollow">theJavaGeek</a></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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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