Почему в equals несколько return?
Для класса Person
со строковыми полями firstName
и lastName
общий вариант для реализации equals
:
@Override
public boolean equals(Object o) {
// self check
if (this == o)return true; //1
// null check
if (o == null) return false; //2
// type check and cast
if (getClass() != o.getClass()) return false; //3
Person person = (Person) o;
// field comparison
return Objects.equals(firstName, person.firstName) //4
&& Objects.equals(lastName, person.lastName);
}
Почему в одном методе перед основным (4)return еще три return? Смысл первого return - если ссылка на разные объекты одна и та же, то они равны. Зачем тогда в конце основной return //4?
Например, упрощу метод для понимания и на выходе получу 4. Зачем нужны первые 3 return?
public int test(Object o) {
if (this == o) return 1; //Рефлексивность
if (o == null) return 2;//Неравенство с null
if (getClass() != o.getClass()) return 3; //симметричность
return 4;
}
Какие поля в классе:
public class MyClass {
double a;
Object b;
private int c; //не участвует в сравнении
public static void main(String[] args) {
MyClass test1 = new MyClass();
test1.a = 3.2;
test1.b = new String("Sек");
MyClass test2 = new MyClass();
System.out.println();
test2.a = 3.2;
test2.b = new String("Sек");
// System.out.println(test1.equals(test2));
System.out.println(test1.test(test2));
}
@Override
public boolean equals(Object o) {
if (this == o) return true; //Рефлексивность
if (o == null) return false;//Неравенство с null
if (getClass() != o.getClass()) return false; //симметричность
MyClass other = (MyClass) o;
//Симметричность, транзитивность
return other.a == this.a && (this.b == null && other.b == null || this.b.equals(other.b));
}
}