[英]equals java unexpected result
I just started learning Java and came across equals. 我刚开始学习Java并遇到了对等问题。 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. Java中的
Object.equals
等于==
,即它测试引用相等性。 Since your Sandbox
class (implicitly) extends Object
, and you don't override equals
, s.equals(s1)
calls Object.equals
. 由于您的
Sandbox
类(隐式)扩展了Object
,并且您没有覆盖equals
,因此s.equals(s1)
调用Object.equals
。
To get the behaviour you want, add an equals
method (override) to your class: 要获得所需的行为,请向类中添加一个
equals
方法(重写):
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
. equals
是可以override
的Object
类方法。
In String
class, it is already overridden. 在
String
类中,它已被覆盖。
If you want your code, to work, you have to define your own equals
method code. 如果要使代码正常工作,则必须定义自己的
equals
方法代码。 Because, obviously, Object
class's code is not valid for sandbox
class. 因为很显然,
Object
类的代码对于sandbox
类无效。
The method signature for equals
is: equals
的方法签名为:
public boolean equals(Object obj);
the difference between ==
and equals
is that ==
checks equality in references and equals
checks equality in value. 之间的差
==
和equals
是==
在引用检查平等和equals
检查平等于值。 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. 除非覆盖,否则
sandbox
的equals
将调用Object
类的equals
。 You should override the equals
function to check equality between you custom objects. 您应该重写
equals
函数,以检查自定义对象之间的equals
性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.