LocalDate in Java has two similar methods equals and isEqual.
What's the difference between them? When do they output different results?
On
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;
}
On
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.
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
LocalDate.equals, like most otherequalsmethod implementations, will always return false if you pass it something other than aLocalDate, even if they represent the same day:ChronoLocalDate.isEqualcompares whether the two dates are the same day, i.e. the same point on the local time line: