tags:

views:

399

answers:

3

I came across a comment in some java code that states that getTime() needs to be called to update the Calendar object. Is this true? I cannot find anything that says that this is necessary.

Here's the code:

Calendar cal = new GregorianCalendar();
cal.setFirstDayOfWeek(Calendar.SUNDAY);
cal.set(2009, 9 - 1, 10, 2, 30);
// Get Time needs to be called to update the Calendar object
cal.getTime();
+4  A: 

No, this is not true.

skaffman
Did it use to be in some prior version of java?
Jeremy Cron
No, never. Existing behaviour is never changed in that way.
skaffman
@Jeremy Cron: no
OscarRyz
Were that true, it would be a good example of terribly designed API.Getter methods should be read only (this is when I miss the const modifier from C++).
abahgat
@abahgat - I agree which is why I questioned it. The developer also didn't assign the result to anything. They just used it as if it didn't return anything.
Jeremy Cron
@abahgat: `java.util.Calendar` *is* a terribly designed API
skaffman
@skaffman - I also agree
Jeremy Cron
A: 

No, it should not be necessary.

Was the Calendar serialized immediate afterwards?

I've been caught by a bug with Calendar serialization in older jvms.

Bug parade bug #4328747

Calling getTime before serialization may be enough to get around the bug, although I don't have a sufficiently old JVM installed for me to confirm that.

Chi
No it wasn't. The workaround for the bug isn't to call getTime() but rather get/setGregorianChange(). I was thinking that this may have been a bug a long time ago (this is older code I'm looking at) but it appears as if that isn't the case.
Jeremy Cron
There were actually several different workarounds that worked, getGregorianChange was one of them, but getTime may have been another of them.anyways, its irrelevant if was wasn't serialized anyways
Chi
+2  A: 

You could be hitting Bug ID 4851640

Calling get(...) / getTime() on a Calendar instance makes isSet(...) useless!

eed3si9n
interesting find....
skaffman
@eed3si9n - good find - I don't think we are using isSet but I will look again.
Jeremy Cron