gpt4 book ai didi

java - 公历 TreeMap

转载 作者:行者123 更新时间:2023-11-30 06:13:59 27 4
gpt4 key购买 nike

我创建了一个 TreeMap<GregorianCalendar, Integer>存储引入 GPS 闰秒的日期:

leapSecondsDict = new TreeMap<GregorianCalendar, Integer>();
GregorianCalendar calendar =
new GregorianCalendar(TimeZone.getTimeZone("UTC"));

calendar.set(1981, GregorianCalendar.JUNE, 30, 23, 59, 59);
leapSecondsDict.put(calendar, 1);
calendar.set(1982, GregorianCalendar.JUNE, 30, 23, 59, 59);
leapSecondsDict.put(calendar, 2);
calendar.set(1983, GregorianCalendar.JUNE, 30, 23, 59, 59);
leapSecondsDict.put(calendar, 3);

问题是每次我调用 put 时,TreeMap仅包含最后插入的元素,大小保持为 1。

为什么会这样?我的猜测是在使用 Calendar 时作为键,键是类实例 id 而不是它的值,所以当将第二个元素插入到 TreeMap 中时我将使用相同的键更新现有条目,即使该键现在是具有不同值的同一类。

我的假设是否正确,还是有其他原因?除了创建一个新的 Calendar 之外,还有什么更好的方法可以实现这一目标吗?对于每个条目?

最佳答案

正如 Balduz 评论的那样:

The set method does not create a new Calendar, it is still the same but with a different value. Therefore, when you add it to the Map it simply updates the value as its the same key, you are always referencing the same object. You need to create a new instance for each of the keys.

因此,您应该每次都创建一个新的,例如:

GregorianCalendar calendar1 = new GregorianCalendar(1981, GregorianCalendar.JUNE, 30, 23, 59, 59);
calendar1.setTimeZone(TimeZone.getTimeZone("UTC"));
leapSecondsDict.put(calendar1, 1);
GregorianCalendar calendar2 = new GregorianCalendar(1982, GregorianCalendar.JUNE, 30, 23, 59, 59);
calendar2.setTimeZone(TimeZone.getTimeZone("UTC"));
leapSecondsDict.put(calendar2, 2);
GregorianCalendar calendar3 = new GregorianCalendar(1983, GregorianCalendar.JUNE, 30, 23, 59, 59);
calendar3.setTimeZone(TimeZone.getTimeZone("UTC"));
leapSecondsDict.put(calendar3, 3);

关于java - 公历 TreeMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31070122/

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