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.equals
in Java is equivalent to ==
, ie it tests reference equality. Since your Sandbox
class (implicitly) extends Object
, and you don't override equals
, s.equals(s1)
calls Object.equals
.
To get the behaviour you want, add an equals
method (override) to your class:
public boolean equals(Object obj) {
if(this == obj) return true;
if(!(obj instanceof Sandbox)) return false;
Sandbox that = (Sandbox)obj;
return this.a == that.a;
}
equals() method in object class, just use == comparison behind the screen. So you got it as false. So you need to override it and give your implementation as needed.
public boolean equals(Object o){
if(o instanceof SandBox){
if(((SandBox)o).a==this.a){
return true;
}
}
return false;
}
This is how it works:
equals
is an Object
class method that you can override
.
In String
class, it is already overridden.
If you want your code, to work, you have to define your own equals
method code. Because, obviously, Object
class's code is not valid for sandbox
class.
The method signature for equals
is:
public boolean equals(Object obj);
the difference between ==
and equals
is that ==
checks equality in references and equals
checks equality in value. tell me please, what is the value of an object? that is why the result is false. unless overridden the equals
of sandbox
will invoke the equals
of the Object
class. You should override the equals
function to check equality between you custom objects.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.