简体   繁体   中英

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. I was just wondering why the return statement of equals() method has to use alternate && and ||? 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)

 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. 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())))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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