为什么具有相同属性和函数的特定类的两个对象在java中不相等?

Fas*_*eem 0 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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

这一行:

if (s1 == s2)
Run Code Online (Sandbox Code Playgroud)

比较变量的值s1s2.这些值只是参考.换句话说,它询问是否值s1s2引用同一个对象.在这种情况下,他们显然没有.

要求价值平等,你通常会打电话equals:

if (s1.equals(s2))
Run Code Online (Sandbox Code Playgroud)

但是,这仍然会返回false,因为您没有覆盖类中的equals方法Student.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!
}
Run Code Online (Sandbox Code Playgroud)