Search code examples
javacalendarlanguage-design

The complete() method in java.util.Calendar


The complete() method in the Calendar class performs the following operations:

protected void complete()

Fills in any unset fields in the calendar fields. First, the computeTime() method is called if the time value (millisecond offset from the Epoch) has not been calculated from calendar field values. Then, the computeFields() method is called to calculate all calendar field values.

the complete() method has the following code:

protected void complete()
    {
        if (!isTimeSet)
        updateTime();
        if (!areFieldsSet || !areAllFieldsSet) {
            computeFields(); // fills in unset fields
            areAllFieldsSet = areFieldsSet = true;
        }
    }

My question is what is the point of this circular work?? First values from

protected int[] fields

are used to update the value of

long time 

using the computeTime() method. And then the value of time is used to update values in fields using computeFields(). The value in both time and fields will be in sync after the call to computeTime() itself, right?? or am i missing something here??

For those who might ask why is it so important, well it is because the order in which the time is recomputed in Calendar often changes the time we get from getTime() (or so i have read)!!


Solution

  • It's not circular.

    Imagine you have a Calendar object with some, but not all, fields set. This method will (a) compute and save the epoch (long time) from the fields that are set, then (b) set all the unset fields to be consistent with the epoch it just computed.

    So when the method completes you'll have a Calendar with all fields filled in and consistent. That is a different, better state of the object from where you started.