This question already has an answer here:
这个问题在这里已有答案:
- How to override equals method in Java 9 answers
如何在Java 9答案中覆盖equals方法
I have a class named student contains two variables name,no and i have created two objects for the class, now i want to check whether both objects are same or not. I am using .equals() method but i am not getting proper output.
我有一个名为student的类包含两个变量name,no和我为该类创建了两个对象,现在我想检查两个对象是否相同。我正在使用.equals()方法,但我没有得到正确的输出。
public class Student {
String name;
int no;
Student(String name,int no){
this.name=name;
this.no=no;
}
public static void main(String[] args) {
Student s1 = new Student("abc", 10);
Student s2 = new Student("abc", 10);
System.out.println(s1.equals(s2));
}
}
output: false
1 个解决方案
#1
2
You haven't provided an implementation of equals
, meaning it will use the default one it inherits from Object
, which is the same as: s1 == s2
, which returns false because they are not the same object.
你还没有提供equals的实现,这意味着它将使用它从Object继承的默认实现,它与:s1 == s2相同,它返回false,因为它们不是同一个对象。
You'll need to provide your own implementation.
您需要提供自己的实现。
Take a look at this.
看看这个。
#1
2
You haven't provided an implementation of equals
, meaning it will use the default one it inherits from Object
, which is the same as: s1 == s2
, which returns false because they are not the same object.
你还没有提供equals的实现,这意味着它将使用它从Object继承的默认实现,它与:s1 == s2相同,它返回false,因为它们不是同一个对象。
You'll need to provide your own implementation.
您需要提供自己的实现。
Take a look at this.
看看这个。