![](/img/trans.png)
[英]Java - How to check if two objects, from the same abstract class, are equal
[英]Why two objects of a specific class with same properties and functions are not equal in java?
在下面的代码中打印“ NotSame”,谁能提前告诉我原因...
public class student {
String name;
student(String name) {
this.name = name;
}
}
public class TestApp{
public static void main(String[] args) {
student s1=new student("A");
student s2=new student("A");
if(s1==s2){
System.out.println("Same");
}else{
System.out.println("NotSame");
}
}
}
这行:
if (s1 == s2)
比较变量s1
和s2
的值。 这些值只是参考。 换句话说,它询问s1
和s2
的值是否指向同一对象。 在这种情况下,他们显然没有。
要要求值相等,通常会调用equals
:
if (s1.equals(s2))
但是,这仍将返回false
,因为您尚未在Student
类中覆盖equals
方法。 Java假定对象身份相等,除非您通过覆盖equals
(和hashCode
)以其他方式告知对象身份。
因此,您可以将代码更改为:
// Not name change to follow Java conventions. The class is now final
// as well for simplicity; equality for non-final classes can be tricky.
public final class Student {
// Equality tests should usually only use final variables. It's odd
// for two objects to be equal and then non-equal.
private final String name;
Student(String name) {
// TODO: Validate that name isn't null
this.name = name;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof Student)) {
return false;
}
Student otherStudent = (Student) other;
return name.equals(otherStudent.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
}
...
Student s1 = new student("A");
Student s2 = new student("A");
if (s1.equals(s2)) {
// Yay!
}
s1
和s2
指向两个具有相同值的不同对象,并且==比较引用而不是对象中的内容 。
原因是两者都是不同的对象,它们不是==
。 当两个实例都指向同一对象时,您将获得"Same"
。
一个真实的例子可以帮助您理解:
拿一个红色的球说那是个红球1。
再取一个红色的球,说那是红色的球2。
两者都是不同的球。 :)
并拿一个红色的球,说那个红球。 稍后,您定义"A ball having color red is a redball"
(正在您的类中实现Object的equals方法)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.