user5620472
user5620472

Reputation: 2892

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)){
...
}

Upvotes: 2

Views: 1972

Answers (1)

Grzegorz Piwowarek
Grzegorz Piwowarek

Reputation: 13853

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.

Upvotes: 3

Related Questions