7

LocalDate in Java has two similar methods equals and isEqual.

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

AlexElin
  • 1,044
  • 14
  • 23
  • Have you read the [documentation](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#isEqual-java.time.chrono.ChronoLocalDate-)? It explains the difference in detail. – Henry Twist May 22 '21 at 09:05
  • @HenryTwist, could you explain it? – AlexElin May 22 '21 at 09:06

3 Answers3

9

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
Sweeper
  • 213,210
  • 22
  • 193
  • 313
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;
}
Most Noble Rabbit
  • 2,728
  • 2
  • 6
  • 12
2

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

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161