Matteo Rizzi
Matteo Rizzi

Reputation: 21

method get of class GregorianCalendar?

I have problems using the class GregorianCalendar in Java. Why does the method get change my variable of type GregorianCalendar?

I do this work:

System.out.println(timestart);
second = timestart.get(GregorianCalendar.SECOND);
System.out.println(timestart);

The output is:

,HOUR_OF_DAY=15,MINUTE=37,SECOND=16,MILLISECOND=794140,ZONE_OFFSET=?,DST_OFFSET=?]
,HOUR=3,HOUR_OF_DAY=15,MINUTE=50,SECOND=30,MILLISECOND=0,ZONE_OFFSET=3600000,DST_OFFSET=3600000]

For simplicity, I have shown the interesting part of the output. I expect that the two prints give the same result, but isn't it.

Upvotes: 2

Views: 110

Answers (1)

kapex
kapex

Reputation: 29959

Looking at the source code of GregorianCalendar and Calendar, you can see that get first calls a method named complete which either calls updateTime or computeFields - a method that calculates fields like minutes, seconds, etc. based on the calendar's timestamp.

Whenever a value is changed, all fields will be invalidated. Fields seem to be only recalculated on access, presumably to avoid unnecessary calculations if you never don't use them. So basically it is lazy loading those fields.

The toString method on the other hand simply prints all values, without recalculating anything. So in your code the first output probably shows old values that are not valid anymore. If this is the case, then you should see something like areFieldsSet=false in the omitted part of the first output.

Upvotes: 1

Related Questions