Search code examples
java-8setjava-timelocaldate

Set<LocalDate> contains LocalDate best practice


I have:

ZoneId gmt = ZoneId.of("GMT");
LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDateNow = localDateTime.toLocalDate();

Set<LocalDate> hollidays = new HashSet<>();

Can I equal LocalDate like this?

if(hollidays.contains(localDateNow)){
...
}

Solution

  • Yes, you can.

    If you have a look at LocalDate::equals() implementation, you will be able to see:

    int compareTo0(LocalDate otherDate) {
        int cmp = (year - otherDate.year);
        if (cmp == 0) {
            cmp = (month - otherDate.month);
            if (cmp == 0) {
                cmp = (day - otherDate.day);
            }
        }
        return cmp;
    }
    

    which looks like a properly implemented equals method for dates - which means it will work properly with HashSets.

    An excerpt from the hashCode() docs:

    If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.