简体   繁体   English

无法理解 Java 中的 equals 方法

[英]Trouble with understanding equals method in Java

I'm learning Java from mooc course and I have problem with understanding this example of writing method that will be comparing objects:我正在从 mooc 课程中学习 Java,我无法理解这个将比较对象的编写方法示例:

public class Person {

private String name;
private int age;
private int weight;
private int height;

// constructors and methods


public boolean equals(Object compared) {
    // if the variables are located in the same position, they are equal
    if (this == compared) {
        return true;
    }

    // if the compared object is not of type Person, the objects are not equal
    if (!(compared instanceof Person)) {
        return false;
    }

    // convert the object into a Person object
    Person comparedPerson = (Person) compared;

    // if the values of the object variables are equal, the objects are equal
    if (this.name.equals(comparedPerson.name) &&
        this.age == comparedPerson.age &&
        this.weight == comparedPerson.weight &&
        this.height == comparedPerson.height) {
        return true;
    }

    // otherwise the objects are not equal
    return false;
}

// .. methods
}

Despite it being commented upon each step, I don't understand the fact that the method keeps going after尽管对每个步骤都进行了评论,但我不明白该方法继续执行的事实

 if (!(compared instanceof Person)) {
        return false;
    } 

So, if "compared" isn't Person type object it returns false, so the method should just stop working, but then there are instructions that enable making it the same type of object that we're comparing it with.因此,如果“比较”不是 Person 类型 object 它返回 false,因此该方法应该停止工作,但是有一些指令可以使其与我们正在比较的 object 类型相同。 Can somebody explain to me, how is it possible that after returning false, the object with "wrong" type can be converted and compared despite not satysfying condition above, which should result in ending the method?有人可以向我解释一下,返回false后,尽管上述条件不满足,但如何转换和比较具有“错误”类型的object,这应该导致方法结束?

If Compared is not a Person the method returns false (ie not equal) and finishes.如果Compared不是Person ,则该方法返回false (即不等于)并结束。
But if you call equals with an object of type Person the condition is not met and the method does not return false but continues.但是,如果您使用Person类型的 object 调用equals ,则不满足条件并且该方法不会返回 false 而是继续。 And if that happens we know compared must be of type Person .如果发生这种情况,我们知道compared必须是Person类型。 But the compiler doesn't know that (it could if it was smarter, but it isn't).但是编译器不知道这一点(如果它更聪明,它可以,但事实并非如此)。 So the line所以这条线

Person comparedPerson = (Person) compared;

does not 'convert' anything.不会“转换”任何东西。 The comment is misleading.该评论具有误导性。 This typecast just tells the compiler our object is in fact of type Person .这种类型转换只是告诉编译器我们的 object 实际上是Person类型。 And this allows the following code to use it as a Person and call Person methods.这允许以下代码将其用作 Person 并调用 Person 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM