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?
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.