I just started learning Java and came across equals. After looking for the difference between equals and ==, I decided to practice it myself but I am not getting the expected results. here is the code:
public class Sandbox {
/**
* @param args
*
*/
private int a;
public void setAtta(int value){a=value;}
public int getAtta(){return a;}
public static void main(String[] args) {
// TODO Auto-generated method stub
Sandbox s = new Sandbox();
s.setAtta(10);
Sandbox s1 = new Sandbox();
s1.setAtta(10);
System.out.println(s==s1);//false- EXPECTED
System.out.println(s.equals(s1));//false- I thought it should be true?
}
}
Object.equalsin Java is equivalent to==, i.e. it tests reference equality. Since yourSandboxclass (implicitly) extendsObject, and you don’t overrideequals,s.equals(s1)callsObject.equals.To get the behaviour you want, add an
equalsmethod (override) to your class: