.equals()方法,比较类的两个对象没有给出确切的结果

时间:2018-10-01 06:10:19

标签: java

我有一个名为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));
    }
}

输出:false

1 个答案:

答案 0 :(得分:2)

您尚未提供equals的实现,这意味着它将使用它从Object继承的默认实现,它与s1 == s2相同,该返回值是false,因为它们不是同一对象。

您需要提供自己的实现。

看看this