Set<LocalDate> 包含 LocalDate 最佳实践
Set<LocalDate> contains LocalDate best practice
我有:
ZoneId gmt = ZoneId.of("GMT");
LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDateNow = localDateTime.toLocalDate();
Set<LocalDate> hollidays = new HashSet<>();
我可以这样等于LocalDate
吗?
if(hollidays.contains(localDateNow)){
...
}
是的,你可以。
如果您查看 LocalDate::equals()
实施,您将能够看到:
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;
}
这看起来像是一个正确实施的 equals
日期方法 - 这意味着它将与 HashSet
s 一起正常工作。
hashCode()
文档的摘录:
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.
我有:
ZoneId gmt = ZoneId.of("GMT");
LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDateNow = localDateTime.toLocalDate();
Set<LocalDate> hollidays = new HashSet<>();
我可以这样等于LocalDate
吗?
if(hollidays.contains(localDateNow)){
...
}
是的,你可以。
如果您查看 LocalDate::equals()
实施,您将能够看到:
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;
}
这看起来像是一个正确实施的 equals
日期方法 - 这意味着它将与 HashSet
s 一起正常工作。
hashCode()
文档的摘录:
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.