简体   繁体   English

为什么覆盖equals()方法的return语句必须使用替代&&和||?

[英]why the return statement of override equals() method has to use alternate && and ||?

I saw the code below online. 我在网上看到下面的代码。 the class override the Object class's hashCode() and equals method. 该类重写Object类的hashCode()和equals方法。 I was just wondering why the return statement of equals() method has to use alternate && and ||? 我只是想知道为什么equals()方法的return语句必须使用替代&&和||? can i just use && all the way through? 我可以一直使用&&吗? is there any particular reason why it has to use alternate && and ||? 有什么特殊原因为什么必须使用替代&&和||?

class Person {

private int id;
private String firstName;
private String lastName;

@Override
public boolean equals(Object obj) {
    if (obj == this) {
        return true;
    }
    if (obj == null || obj.getClass() != this.getClass()) {
        return false;
    }

    Person guest = (Person) obj;
    return id == guest.id
            && ((firstName == null ? guest.firstName == null : firstName.equals(guest.firstName))
            || (firstName != null && firstName.equals(guest.getFirstName())))
            && ((lastName == null ? guest.lastName == null : lastName.equals(guest.lastName))
            || (lastName != null && lastName.equals(guest.getLastName())));
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result
            + ((firstName == null) ? 0 : firstName.hashCode());
    result = prime * result + id;
    result = prime * result
            + ((lastName == null) ? 0 : lastName.hashCode());
    return result;
}



}

Both disjunctions can be replaced with the first operand of || 这两个析取符都可以替换为||的第一个操作数。 , since the second operator just covers the second alternative of the tenary operator again (assuming the getter returns the field value) ,因为第二个运算符仅再次覆盖了tenary运算符的第二个替代项(假设getter返回字段值)

 id == guest.id
        && (firstName == null ? guest.firstName == null : firstName.equals(guest.firstName))
        && (lastName == null ? guest.lastName == null : lastName.equals(guest.lastName));

But I recommend rewriting it as 但我建议将其重写为

id == guest.id
        && Objects.equals(firstName, guest.firstName)
        && Objects.equals(lastName, guest.lastName);

The OR condition is used depending of the value of first name or last name respectively taken into account if they are null out not. 如果不是null值,则根据分别考虑的名字或姓氏的值使用或条件。 But that condition is already checked in the second part of the ternary ? 但是那个条件已经在三元组的第二部分中检查了吗? : Operator, so you can remove the OR part. :运算符,因此您可以删除“或”部分。 The result will be the same 结果将是相同的

((firstName == null ? guest.firstName == null : firstName.equals(guest.firstName)) || (firstName != null && firstName.equals(guest.getFirstName())))

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

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