'LocalDate: equals vs isEqual
LocalDate in Java has two similar methods equals and isEqual.
What's the difference between them? When do they output different results?
Solution 1:[1]
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
Solution 2:[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;
}
Solution 3:[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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sweeper |
| Solution 2 | |
| Solution 3 |
