LocalDate: equals vs isEqual
Asked Answered
C

3

8

LocalDate in Java has two similar methods equals and isEqual.

What's the difference between them? When do they output different results?

Carpophore answered 22/5, 2021 at 9:1 Comment(2)
Have you read the documentation? It explains the difference in detail.Screwy
@HenryTwist, could you explain it?Carpophore
C
12

LocalDate.equals, like most other equals method implementations, will always return false if you pass it something other than a LocalDate, even if they represent the same day:

System.out.println(LocalDate.now().equals(HijrahDate.now())); // false

ChronoLocalDate.isEqual compares whether the two dates are the same day, i.e. the same point on the local time line:

System.out.println(LocalDate.now().isEqual(HijrahDate.now())); // true
Catamite answered 22/5, 2021 at 9:10 Comment(0)
U
3

equals() can handle any reference type

There are two good answers. For the sake of completeness I want to make explicit that the observation by Most Needed Rabbit implies that you can pass something that isn’t a ChronoLocalDate to equals() but not to isEqual(). For example:

    System.out.println(LocalDate.of(2021, Month.MAY, 26).equals("2021-05-26"));

Output:

false

This is standard behaviour of the equals method in Java.

Trying to use isEqual() similarly gives a compile error:

    System.out.println(LocalDate.of(2021, Month.MAY, 26).isEqual("2021-05-26"));

The method isEqual(ChronoLocalDate) in the type LocalDate is not applicable for the arguments (String)

Passing a string or yet a different type is not often useful, though.

equals() tolerates null; isEqual() does not

Possibly a bit more surprisingly the two methods also treat null differently.

    System.out.println(LocalDate.of(2021, Month.MAY, 26).equals(null));

false

    System.out.println(LocalDate.of(2021, Month.MAY, 26).isEqual(null));

Exception in thread "main" java.lang.NullPointerException

Unconventionality answered 26/5, 2021 at 4:59 Comment(0)
H
2

The equals() method will give the same result as isEqual(), but only if the argument passed is of the same type (in this case, LocalDate).

isEqual() can be called with a ChronoLocalDate (JapaneseDate, ThaiBuddhistDate...)

public boolean isEqual(ChronoLocalDate other)

equals() will return false if the argument is not a LocalDate:

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj instanceof LocalDate) {
        return compareTo0((LocalDate) obj) == 0;
    }
    return false;
}
Health answered 22/5, 2021 at 9:7 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.