gpt4 book ai didi

java - 在 LocalDate 对象上使用 equals 和 ==

转载 作者:行者123 更新时间:2023-11-29 04:49:16 26 4
gpt4 key购买 nike

我有以下代码:

LocalDate one = LocalDate.of(2016, 1, 1);
LocalDate two = LocalDate.of(2016, 1, 1);
System.out.println(one.equals(two)); // true since contents are same
System.out.println(one == two); // false since references are diff
LocalDate newone = one.with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY));
System.out.println(newone.equals(one));// true since contents are still same
System.out.println(newone == one); //-4- why true here

问题是为什么在 4 时它给出 true,因为 LocalDate 对象是不可变的,所以用 TemporalAdjuster 改变一个对象会给出一个新的 LocalDate 对象。如果newone和one的内容不一样

newone == one returns false

请更新此行为。谢谢

最佳答案

看一下TemporalAdjusters.nextOrSame的代码:

public static TemporalAdjuster nextOrSame(DayOfWeek dayOfWeek) {
int dowValue = dayOfWeek.getValue();
return (temporal) -> {
int calDow = temporal.get(DAY_OF_WEEK);
if (calDow == dowValue) {
return temporal; // <-- returns the original object!
}
int daysDiff = calDow - dowValue;
return temporal.plus(daysDiff >= 0 ? 7 - daysDiff : -daysDiff, DAYS);
};
}

来自documentation (强调我的):

Returns the next-or-same day-of-week adjuster, which adjusts the date to the first occurrence of the specified day-of-week after the date being adjusted unless it is already on that day in which case the same object is returned.

因此,如果不需要调整(因为 2016 年 1 月 1 日星期五),则返回相同对象。

关于java - 在 LocalDate 对象上使用 equals 和 ==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36042134/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com