TreeMap of GregorianCalendars

时间:2015-06-26 09:52:43

标签: java treemap

I have created a TreeMap of <GregorianCalendar, Integer> to store the dates in which GPS leap seconds were introduced:

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);

The problem is that each time I call put, the TreeMap contains only the last inserted element, and the size stays 1.

Why is this happening? My guess is that when using the Calendar as a key, the key is the class instance id and not its value, so when inserting the second element into the TreeMap I would be updating an existing entry with the same key, even if that key is now the same class with a different value.

Is my assumption right, or is there any other reason? Is there any farcier way of achieving this other than creating a new Calendar for each entry?

2 个答案:

答案 0 :(得分:3)

正如Balduz评论的那样:

  

set方法不会创建新的Calendar,它仍然是相同的但具有不同的值。因此,当您将其添加到Map时,它只是将值更新为相同的键,您始终引用相同的对象。您需要为每个键创建一个新实例。

所以,你应该每次创建一个新的,例如:

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);

答案 1 :(得分:2)

set方法不会创建新的Calendar,但它仍然相同但具有不同的值。因此,当您将其添加到Map时,它只是将值更新为相同的键,您始终引用相同的对象。您需要为每个键创建一个新实例。