rt/emul/compact/src/main/java/java/util/Calendar.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 04 Oct 2013 12:01:56 +0200
changeset 1340 41046f76a76a
parent 1334 588d5bf7a560
permissions -rw-r--r--
Somehow implementing the calendar classes so they compile
     1 /*
     2  * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    25 
    26 /*
    27  * (C) Copyright Taligent, Inc. 1996-1998 - All Rights Reserved
    28  * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
    29  *
    30  *   The original version of this source code and documentation is copyrighted
    31  * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
    32  * materials are provided under terms of a License Agreement between Taligent
    33  * and Sun. This technology is protected by multiple US and International
    34  * patents. This notice and attribution to Taligent may not be removed.
    35  *   Taligent is a registered trademark of Taligent, Inc.
    36  *
    37  */
    38 
    39 package java.util;
    40 
    41 import java.io.IOException;
    42 import java.io.ObjectInputStream;
    43 import java.io.ObjectOutputStream;
    44 import java.io.OptionalDataException;
    45 import java.io.Serializable;
    46 import java.security.AccessController;
    47 import java.security.PrivilegedActionException;
    48 import java.security.PrivilegedExceptionAction;
    49 import java.text.DateFormat;
    50 import java.text.DateFormatSymbols;
    51 import java.util.concurrent.ConcurrentHashMap;
    52 import java.util.concurrent.ConcurrentMap;
    53 
    54 /**
    55  * The <code>Calendar</code> class is an abstract class that provides methods
    56  * for converting between a specific instant in time and a set of {@link
    57  * #fields calendar fields} such as <code>YEAR</code>, <code>MONTH</code>,
    58  * <code>DAY_OF_MONTH</code>, <code>HOUR</code>, and so on, and for
    59  * manipulating the calendar fields, such as getting the date of the next
    60  * week. An instant in time can be represented by a millisecond value that is
    61  * an offset from the <a name="Epoch"><em>Epoch</em></a>, January 1, 1970
    62  * 00:00:00.000 GMT (Gregorian).
    63  *
    64  * <p>The class also provides additional fields and methods for
    65  * implementing a concrete calendar system outside the package. Those
    66  * fields and methods are defined as <code>protected</code>.
    67  *
    68  * <p>
    69  * Like other locale-sensitive classes, <code>Calendar</code> provides a
    70  * class method, <code>getInstance</code>, for getting a generally useful
    71  * object of this type. <code>Calendar</code>'s <code>getInstance</code> method
    72  * returns a <code>Calendar</code> object whose
    73  * calendar fields have been initialized with the current date and time:
    74  * <blockquote>
    75  * <pre>
    76  *     Calendar rightNow = Calendar.getInstance();
    77  * </pre>
    78  * </blockquote>
    79  *
    80  * <p>A <code>Calendar</code> object can produce all the calendar field values
    81  * needed to implement the date-time formatting for a particular language and
    82  * calendar style (for example, Japanese-Gregorian, Japanese-Traditional).
    83  * <code>Calendar</code> defines the range of values returned by
    84  * certain calendar fields, as well as their meaning.  For example,
    85  * the first month of the calendar system has value <code>MONTH ==
    86  * JANUARY</code> for all calendars.  Other values are defined by the
    87  * concrete subclass, such as <code>ERA</code>.  See individual field
    88  * documentation and subclass documentation for details.
    89  *
    90  * <h4>Getting and Setting Calendar Field Values</h4>
    91  *
    92  * <p>The calendar field values can be set by calling the <code>set</code>
    93  * methods. Any field values set in a <code>Calendar</code> will not be
    94  * interpreted until it needs to calculate its time value (milliseconds from
    95  * the Epoch) or values of the calendar fields. Calling the
    96  * <code>get</code>, <code>getTimeInMillis</code>, <code>getTime</code>,
    97  * <code>add</code> and <code>roll</code> involves such calculation.
    98  *
    99  * <h4>Leniency</h4>
   100  *
   101  * <p><code>Calendar</code> has two modes for interpreting the calendar
   102  * fields, <em>lenient</em> and <em>non-lenient</em>.  When a
   103  * <code>Calendar</code> is in lenient mode, it accepts a wider range of
   104  * calendar field values than it produces.  When a <code>Calendar</code>
   105  * recomputes calendar field values for return by <code>get()</code>, all of
   106  * the calendar fields are normalized. For example, a lenient
   107  * <code>GregorianCalendar</code> interprets <code>MONTH == JANUARY</code>,
   108  * <code>DAY_OF_MONTH == 32</code> as February 1.
   109 
   110  * <p>When a <code>Calendar</code> is in non-lenient mode, it throws an
   111  * exception if there is any inconsistency in its calendar fields. For
   112  * example, a <code>GregorianCalendar</code> always produces
   113  * <code>DAY_OF_MONTH</code> values between 1 and the length of the month. A
   114  * non-lenient <code>GregorianCalendar</code> throws an exception upon
   115  * calculating its time or calendar field values if any out-of-range field
   116  * value has been set.
   117  *
   118  * <h4><a name="first_week">First Week</a></h4>
   119  *
   120  * <code>Calendar</code> defines a locale-specific seven day week using two
   121  * parameters: the first day of the week and the minimal days in first week
   122  * (from 1 to 7).  These numbers are taken from the locale resource data when a
   123  * <code>Calendar</code> is constructed.  They may also be specified explicitly
   124  * through the methods for setting their values.
   125  *
   126  * <p>When setting or getting the <code>WEEK_OF_MONTH</code> or
   127  * <code>WEEK_OF_YEAR</code> fields, <code>Calendar</code> must determine the
   128  * first week of the month or year as a reference point.  The first week of a
   129  * month or year is defined as the earliest seven day period beginning on
   130  * <code>getFirstDayOfWeek()</code> and containing at least
   131  * <code>getMinimalDaysInFirstWeek()</code> days of that month or year.  Weeks
   132  * numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow
   133  * it.  Note that the normalized numbering returned by <code>get()</code> may be
   134  * different.  For example, a specific <code>Calendar</code> subclass may
   135  * designate the week before week 1 of a year as week <code><i>n</i></code> of
   136  * the previous year.
   137  *
   138  * <h4>Calendar Fields Resolution</h4>
   139  *
   140  * When computing a date and time from the calendar fields, there
   141  * may be insufficient information for the computation (such as only
   142  * year and month with no day of month), or there may be inconsistent
   143  * information (such as Tuesday, July 15, 1996 (Gregorian) -- July 15,
   144  * 1996 is actually a Monday). <code>Calendar</code> will resolve
   145  * calendar field values to determine the date and time in the
   146  * following way.
   147  *
   148  * <p>If there is any conflict in calendar field values,
   149  * <code>Calendar</code> gives priorities to calendar fields that have been set
   150  * more recently. The following are the default combinations of the
   151  * calendar fields. The most recent combination, as determined by the
   152  * most recently set single field, will be used.
   153  *
   154  * <p><a name="date_resolution">For the date fields</a>:
   155  * <blockquote>
   156  * <pre>
   157  * YEAR + MONTH + DAY_OF_MONTH
   158  * YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
   159  * YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
   160  * YEAR + DAY_OF_YEAR
   161  * YEAR + DAY_OF_WEEK + WEEK_OF_YEAR
   162  * </pre></blockquote>
   163  *
   164  * <a name="time_resolution">For the time of day fields</a>:
   165  * <blockquote>
   166  * <pre>
   167  * HOUR_OF_DAY
   168  * AM_PM + HOUR
   169  * </pre></blockquote>
   170  *
   171  * <p>If there are any calendar fields whose values haven't been set in the selected
   172  * field combination, <code>Calendar</code> uses their default values. The default
   173  * value of each field may vary by concrete calendar systems. For example, in
   174  * <code>GregorianCalendar</code>, the default of a field is the same as that
   175  * of the start of the Epoch: i.e., <code>YEAR = 1970</code>, <code>MONTH =
   176  * JANUARY</code>, <code>DAY_OF_MONTH = 1</code>, etc.
   177  *
   178  * <p>
   179  * <strong>Note:</strong> There are certain possible ambiguities in
   180  * interpretation of certain singular times, which are resolved in the
   181  * following ways:
   182  * <ol>
   183  *     <li> 23:59 is the last minute of the day and 00:00 is the first
   184  *          minute of the next day. Thus, 23:59 on Dec 31, 1999 &lt; 00:00 on
   185  *          Jan 1, 2000 &lt; 00:01 on Jan 1, 2000.
   186  *
   187  *     <li> Although historically not precise, midnight also belongs to "am",
   188  *          and noon belongs to "pm", so on the same day,
   189  *          12:00 am (midnight) &lt; 12:01 am, and 12:00 pm (noon) &lt; 12:01 pm
   190  * </ol>
   191  *
   192  * <p>
   193  * The date or time format strings are not part of the definition of a
   194  * calendar, as those must be modifiable or overridable by the user at
   195  * runtime. Use {@link DateFormat}
   196  * to format dates.
   197  *
   198  * <h4>Field Manipulation</h4>
   199  *
   200  * The calendar fields can be changed using three methods:
   201  * <code>set()</code>, <code>add()</code>, and <code>roll()</code>.</p>
   202  *
   203  * <p><strong><code>set(f, value)</code></strong> changes calendar field
   204  * <code>f</code> to <code>value</code>.  In addition, it sets an
   205  * internal member variable to indicate that calendar field <code>f</code> has
   206  * been changed. Although calendar field <code>f</code> is changed immediately,
   207  * the calendar's time value in milliseconds is not recomputed until the next call to
   208  * <code>get()</code>, <code>getTime()</code>, <code>getTimeInMillis()</code>,
   209  * <code>add()</code>, or <code>roll()</code> is made. Thus, multiple calls to
   210  * <code>set()</code> do not trigger multiple, unnecessary
   211  * computations. As a result of changing a calendar field using
   212  * <code>set()</code>, other calendar fields may also change, depending on the
   213  * calendar field, the calendar field value, and the calendar system. In addition,
   214  * <code>get(f)</code> will not necessarily return <code>value</code> set by
   215  * the call to the <code>set</code> method
   216  * after the calendar fields have been recomputed. The specifics are determined by
   217  * the concrete calendar class.</p>
   218  *
   219  * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
   220  * originally set to August 31, 1999. Calling <code>set(Calendar.MONTH,
   221  * Calendar.SEPTEMBER)</code> sets the date to September 31,
   222  * 1999. This is a temporary internal representation that resolves to
   223  * October 1, 1999 if <code>getTime()</code>is then called. However, a
   224  * call to <code>set(Calendar.DAY_OF_MONTH, 30)</code> before the call to
   225  * <code>getTime()</code> sets the date to September 30, 1999, since
   226  * no recomputation occurs after <code>set()</code> itself.</p>
   227  *
   228  * <p><strong><code>add(f, delta)</code></strong> adds <code>delta</code>
   229  * to field <code>f</code>.  This is equivalent to calling <code>set(f,
   230  * get(f) + delta)</code> with two adjustments:</p>
   231  *
   232  * <blockquote>
   233  *   <p><strong>Add rule 1</strong>. The value of field <code>f</code>
   234  *   after the call minus the value of field <code>f</code> before the
   235  *   call is <code>delta</code>, modulo any overflow that has occurred in
   236  *   field <code>f</code>. Overflow occurs when a field value exceeds its
   237  *   range and, as a result, the next larger field is incremented or
   238  *   decremented and the field value is adjusted back into its range.</p>
   239  *
   240  *   <p><strong>Add rule 2</strong>. If a smaller field is expected to be
   241  *   invariant, but it is impossible for it to be equal to its
   242  *   prior value because of changes in its minimum or maximum after field
   243  *   <code>f</code> is changed or other constraints, such as time zone
   244  *   offset changes, then its value is adjusted to be as close
   245  *   as possible to its expected value. A smaller field represents a
   246  *   smaller unit of time. <code>HOUR</code> is a smaller field than
   247  *   <code>DAY_OF_MONTH</code>. No adjustment is made to smaller fields
   248  *   that are not expected to be invariant. The calendar system
   249  *   determines what fields are expected to be invariant.</p>
   250  * </blockquote>
   251  *
   252  * <p>In addition, unlike <code>set()</code>, <code>add()</code> forces
   253  * an immediate recomputation of the calendar's milliseconds and all
   254  * fields.</p>
   255  *
   256  * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
   257  * originally set to August 31, 1999. Calling <code>add(Calendar.MONTH,
   258  * 13)</code> sets the calendar to September 30, 2000. <strong>Add rule
   259  * 1</strong> sets the <code>MONTH</code> field to September, since
   260  * adding 13 months to August gives September of the next year. Since
   261  * <code>DAY_OF_MONTH</code> cannot be 31 in September in a
   262  * <code>GregorianCalendar</code>, <strong>add rule 2</strong> sets the
   263  * <code>DAY_OF_MONTH</code> to 30, the closest possible value. Although
   264  * it is a smaller field, <code>DAY_OF_WEEK</code> is not adjusted by
   265  * rule 2, since it is expected to change when the month changes in a
   266  * <code>GregorianCalendar</code>.</p>
   267  *
   268  * <p><strong><code>roll(f, delta)</code></strong> adds
   269  * <code>delta</code> to field <code>f</code> without changing larger
   270  * fields. This is equivalent to calling <code>add(f, delta)</code> with
   271  * the following adjustment:</p>
   272  *
   273  * <blockquote>
   274  *   <p><strong>Roll rule</strong>. Larger fields are unchanged after the
   275  *   call. A larger field represents a larger unit of
   276  *   time. <code>DAY_OF_MONTH</code> is a larger field than
   277  *   <code>HOUR</code>.</p>
   278  * </blockquote>
   279  *
   280  * <p><em>Example</em>: See {@link java.util.GregorianCalendar#roll(int, int)}.
   281  *
   282  * <p><strong>Usage model</strong>. To motivate the behavior of
   283  * <code>add()</code> and <code>roll()</code>, consider a user interface
   284  * component with increment and decrement buttons for the month, day, and
   285  * year, and an underlying <code>GregorianCalendar</code>. If the
   286  * interface reads January 31, 1999 and the user presses the month
   287  * increment button, what should it read? If the underlying
   288  * implementation uses <code>set()</code>, it might read March 3, 1999. A
   289  * better result would be February 28, 1999. Furthermore, if the user
   290  * presses the month increment button again, it should read March 31,
   291  * 1999, not March 28, 1999. By saving the original date and using either
   292  * <code>add()</code> or <code>roll()</code>, depending on whether larger
   293  * fields should be affected, the user interface can behave as most users
   294  * will intuitively expect.</p>
   295  *
   296  * @see          java.lang.System#currentTimeMillis()
   297  * @see          Date
   298  * @see          GregorianCalendar
   299  * @see          TimeZone
   300  * @see          java.text.DateFormat
   301  * @author Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu
   302  * @since JDK1.1
   303  */
   304 public abstract class Calendar implements Serializable, Cloneable, Comparable<Calendar> {
   305 
   306     // Data flow in Calendar
   307     // ---------------------
   308 
   309     // The current time is represented in two ways by Calendar: as UTC
   310     // milliseconds from the epoch (1 January 1970 0:00 UTC), and as local
   311     // fields such as MONTH, HOUR, AM_PM, etc.  It is possible to compute the
   312     // millis from the fields, and vice versa.  The data needed to do this
   313     // conversion is encapsulated by a TimeZone object owned by the Calendar.
   314     // The data provided by the TimeZone object may also be overridden if the
   315     // user sets the ZONE_OFFSET and/or DST_OFFSET fields directly. The class
   316     // keeps track of what information was most recently set by the caller, and
   317     // uses that to compute any other information as needed.
   318 
   319     // If the user sets the fields using set(), the data flow is as follows.
   320     // This is implemented by the Calendar subclass's computeTime() method.
   321     // During this process, certain fields may be ignored.  The disambiguation
   322     // algorithm for resolving which fields to pay attention to is described
   323     // in the class documentation.
   324 
   325     //   local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
   326     //           |
   327     //           | Using Calendar-specific algorithm
   328     //           V
   329     //   local standard millis
   330     //           |
   331     //           | Using TimeZone or user-set ZONE_OFFSET / DST_OFFSET
   332     //           V
   333     //   UTC millis (in time data member)
   334 
   335     // If the user sets the UTC millis using setTime() or setTimeInMillis(),
   336     // the data flow is as follows.  This is implemented by the Calendar
   337     // subclass's computeFields() method.
   338 
   339     //   UTC millis (in time data member)
   340     //           |
   341     //           | Using TimeZone getOffset()
   342     //           V
   343     //   local standard millis
   344     //           |
   345     //           | Using Calendar-specific algorithm
   346     //           V
   347     //   local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
   348 
   349     // In general, a round trip from fields, through local and UTC millis, and
   350     // back out to fields is made when necessary.  This is implemented by the
   351     // complete() method.  Resolving a partial set of fields into a UTC millis
   352     // value allows all remaining fields to be generated from that value.  If
   353     // the Calendar is lenient, the fields are also renormalized to standard
   354     // ranges when they are regenerated.
   355 
   356     /**
   357      * Field number for <code>get</code> and <code>set</code> indicating the
   358      * era, e.g., AD or BC in the Julian calendar. This is a calendar-specific
   359      * value; see subclass documentation.
   360      *
   361      * @see GregorianCalendar#AD
   362      * @see GregorianCalendar#BC
   363      */
   364     public final static int ERA = 0;
   365 
   366     /**
   367      * Field number for <code>get</code> and <code>set</code> indicating the
   368      * year. This is a calendar-specific value; see subclass documentation.
   369      */
   370     public final static int YEAR = 1;
   371 
   372     /**
   373      * Field number for <code>get</code> and <code>set</code> indicating the
   374      * month. This is a calendar-specific value. The first month of
   375      * the year in the Gregorian and Julian calendars is
   376      * <code>JANUARY</code> which is 0; the last depends on the number
   377      * of months in a year.
   378      *
   379      * @see #JANUARY
   380      * @see #FEBRUARY
   381      * @see #MARCH
   382      * @see #APRIL
   383      * @see #MAY
   384      * @see #JUNE
   385      * @see #JULY
   386      * @see #AUGUST
   387      * @see #SEPTEMBER
   388      * @see #OCTOBER
   389      * @see #NOVEMBER
   390      * @see #DECEMBER
   391      * @see #UNDECIMBER
   392      */
   393     public final static int MONTH = 2;
   394 
   395     /**
   396      * Field number for <code>get</code> and <code>set</code> indicating the
   397      * week number within the current year.  The first week of the year, as
   398      * defined by <code>getFirstDayOfWeek()</code> and
   399      * <code>getMinimalDaysInFirstWeek()</code>, has value 1.  Subclasses define
   400      * the value of <code>WEEK_OF_YEAR</code> for days before the first week of
   401      * the year.
   402      *
   403      * @see #getFirstDayOfWeek
   404      * @see #getMinimalDaysInFirstWeek
   405      */
   406     public final static int WEEK_OF_YEAR = 3;
   407 
   408     /**
   409      * Field number for <code>get</code> and <code>set</code> indicating the
   410      * week number within the current month.  The first week of the month, as
   411      * defined by <code>getFirstDayOfWeek()</code> and
   412      * <code>getMinimalDaysInFirstWeek()</code>, has value 1.  Subclasses define
   413      * the value of <code>WEEK_OF_MONTH</code> for days before the first week of
   414      * the month.
   415      *
   416      * @see #getFirstDayOfWeek
   417      * @see #getMinimalDaysInFirstWeek
   418      */
   419     public final static int WEEK_OF_MONTH = 4;
   420 
   421     /**
   422      * Field number for <code>get</code> and <code>set</code> indicating the
   423      * day of the month. This is a synonym for <code>DAY_OF_MONTH</code>.
   424      * The first day of the month has value 1.
   425      *
   426      * @see #DAY_OF_MONTH
   427      */
   428     public final static int DATE = 5;
   429 
   430     /**
   431      * Field number for <code>get</code> and <code>set</code> indicating the
   432      * day of the month. This is a synonym for <code>DATE</code>.
   433      * The first day of the month has value 1.
   434      *
   435      * @see #DATE
   436      */
   437     public final static int DAY_OF_MONTH = 5;
   438 
   439     /**
   440      * Field number for <code>get</code> and <code>set</code> indicating the day
   441      * number within the current year.  The first day of the year has value 1.
   442      */
   443     public final static int DAY_OF_YEAR = 6;
   444 
   445     /**
   446      * Field number for <code>get</code> and <code>set</code> indicating the day
   447      * of the week.  This field takes values <code>SUNDAY</code>,
   448      * <code>MONDAY</code>, <code>TUESDAY</code>, <code>WEDNESDAY</code>,
   449      * <code>THURSDAY</code>, <code>FRIDAY</code>, and <code>SATURDAY</code>.
   450      *
   451      * @see #SUNDAY
   452      * @see #MONDAY
   453      * @see #TUESDAY
   454      * @see #WEDNESDAY
   455      * @see #THURSDAY
   456      * @see #FRIDAY
   457      * @see #SATURDAY
   458      */
   459     public final static int DAY_OF_WEEK = 7;
   460 
   461     /**
   462      * Field number for <code>get</code> and <code>set</code> indicating the
   463      * ordinal number of the day of the week within the current month. Together
   464      * with the <code>DAY_OF_WEEK</code> field, this uniquely specifies a day
   465      * within a month.  Unlike <code>WEEK_OF_MONTH</code> and
   466      * <code>WEEK_OF_YEAR</code>, this field's value does <em>not</em> depend on
   467      * <code>getFirstDayOfWeek()</code> or
   468      * <code>getMinimalDaysInFirstWeek()</code>.  <code>DAY_OF_MONTH 1</code>
   469      * through <code>7</code> always correspond to <code>DAY_OF_WEEK_IN_MONTH
   470      * 1</code>; <code>8</code> through <code>14</code> correspond to
   471      * <code>DAY_OF_WEEK_IN_MONTH 2</code>, and so on.
   472      * <code>DAY_OF_WEEK_IN_MONTH 0</code> indicates the week before
   473      * <code>DAY_OF_WEEK_IN_MONTH 1</code>.  Negative values count back from the
   474      * end of the month, so the last Sunday of a month is specified as
   475      * <code>DAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1</code>.  Because
   476      * negative values count backward they will usually be aligned differently
   477      * within the month than positive values.  For example, if a month has 31
   478      * days, <code>DAY_OF_WEEK_IN_MONTH -1</code> will overlap
   479      * <code>DAY_OF_WEEK_IN_MONTH 5</code> and the end of <code>4</code>.
   480      *
   481      * @see #DAY_OF_WEEK
   482      * @see #WEEK_OF_MONTH
   483      */
   484     public final static int DAY_OF_WEEK_IN_MONTH = 8;
   485 
   486     /**
   487      * Field number for <code>get</code> and <code>set</code> indicating
   488      * whether the <code>HOUR</code> is before or after noon.
   489      * E.g., at 10:04:15.250 PM the <code>AM_PM</code> is <code>PM</code>.
   490      *
   491      * @see #AM
   492      * @see #PM
   493      * @see #HOUR
   494      */
   495     public final static int AM_PM = 9;
   496 
   497     /**
   498      * Field number for <code>get</code> and <code>set</code> indicating the
   499      * hour of the morning or afternoon. <code>HOUR</code> is used for the
   500      * 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12.
   501      * E.g., at 10:04:15.250 PM the <code>HOUR</code> is 10.
   502      *
   503      * @see #AM_PM
   504      * @see #HOUR_OF_DAY
   505      */
   506     public final static int HOUR = 10;
   507 
   508     /**
   509      * Field number for <code>get</code> and <code>set</code> indicating the
   510      * hour of the day. <code>HOUR_OF_DAY</code> is used for the 24-hour clock.
   511      * E.g., at 10:04:15.250 PM the <code>HOUR_OF_DAY</code> is 22.
   512      *
   513      * @see #HOUR
   514      */
   515     public final static int HOUR_OF_DAY = 11;
   516 
   517     /**
   518      * Field number for <code>get</code> and <code>set</code> indicating the
   519      * minute within the hour.
   520      * E.g., at 10:04:15.250 PM the <code>MINUTE</code> is 4.
   521      */
   522     public final static int MINUTE = 12;
   523 
   524     /**
   525      * Field number for <code>get</code> and <code>set</code> indicating the
   526      * second within the minute.
   527      * E.g., at 10:04:15.250 PM the <code>SECOND</code> is 15.
   528      */
   529     public final static int SECOND = 13;
   530 
   531     /**
   532      * Field number for <code>get</code> and <code>set</code> indicating the
   533      * millisecond within the second.
   534      * E.g., at 10:04:15.250 PM the <code>MILLISECOND</code> is 250.
   535      */
   536     public final static int MILLISECOND = 14;
   537 
   538     /**
   539      * Field number for <code>get</code> and <code>set</code>
   540      * indicating the raw offset from GMT in milliseconds.
   541      * <p>
   542      * This field reflects the correct GMT offset value of the time
   543      * zone of this <code>Calendar</code> if the
   544      * <code>TimeZone</code> implementation subclass supports
   545      * historical GMT offset changes.
   546      */
   547     public final static int ZONE_OFFSET = 15;
   548 
   549     /**
   550      * Field number for <code>get</code> and <code>set</code> indicating the
   551      * daylight saving offset in milliseconds.
   552      * <p>
   553      * This field reflects the correct daylight saving offset value of
   554      * the time zone of this <code>Calendar</code> if the
   555      * <code>TimeZone</code> implementation subclass supports
   556      * historical Daylight Saving Time schedule changes.
   557      */
   558     public final static int DST_OFFSET = 16;
   559 
   560     /**
   561      * The number of distinct fields recognized by <code>get</code> and <code>set</code>.
   562      * Field numbers range from <code>0..FIELD_COUNT-1</code>.
   563      */
   564     public final static int FIELD_COUNT = 17;
   565 
   566     /**
   567      * Value of the {@link #DAY_OF_WEEK} field indicating
   568      * Sunday.
   569      */
   570     public final static int SUNDAY = 1;
   571 
   572     /**
   573      * Value of the {@link #DAY_OF_WEEK} field indicating
   574      * Monday.
   575      */
   576     public final static int MONDAY = 2;
   577 
   578     /**
   579      * Value of the {@link #DAY_OF_WEEK} field indicating
   580      * Tuesday.
   581      */
   582     public final static int TUESDAY = 3;
   583 
   584     /**
   585      * Value of the {@link #DAY_OF_WEEK} field indicating
   586      * Wednesday.
   587      */
   588     public final static int WEDNESDAY = 4;
   589 
   590     /**
   591      * Value of the {@link #DAY_OF_WEEK} field indicating
   592      * Thursday.
   593      */
   594     public final static int THURSDAY = 5;
   595 
   596     /**
   597      * Value of the {@link #DAY_OF_WEEK} field indicating
   598      * Friday.
   599      */
   600     public final static int FRIDAY = 6;
   601 
   602     /**
   603      * Value of the {@link #DAY_OF_WEEK} field indicating
   604      * Saturday.
   605      */
   606     public final static int SATURDAY = 7;
   607 
   608     /**
   609      * Value of the {@link #MONTH} field indicating the
   610      * first month of the year in the Gregorian and Julian calendars.
   611      */
   612     public final static int JANUARY = 0;
   613 
   614     /**
   615      * Value of the {@link #MONTH} field indicating the
   616      * second month of the year in the Gregorian and Julian calendars.
   617      */
   618     public final static int FEBRUARY = 1;
   619 
   620     /**
   621      * Value of the {@link #MONTH} field indicating the
   622      * third month of the year in the Gregorian and Julian calendars.
   623      */
   624     public final static int MARCH = 2;
   625 
   626     /**
   627      * Value of the {@link #MONTH} field indicating the
   628      * fourth month of the year in the Gregorian and Julian calendars.
   629      */
   630     public final static int APRIL = 3;
   631 
   632     /**
   633      * Value of the {@link #MONTH} field indicating the
   634      * fifth month of the year in the Gregorian and Julian calendars.
   635      */
   636     public final static int MAY = 4;
   637 
   638     /**
   639      * Value of the {@link #MONTH} field indicating the
   640      * sixth month of the year in the Gregorian and Julian calendars.
   641      */
   642     public final static int JUNE = 5;
   643 
   644     /**
   645      * Value of the {@link #MONTH} field indicating the
   646      * seventh month of the year in the Gregorian and Julian calendars.
   647      */
   648     public final static int JULY = 6;
   649 
   650     /**
   651      * Value of the {@link #MONTH} field indicating the
   652      * eighth month of the year in the Gregorian and Julian calendars.
   653      */
   654     public final static int AUGUST = 7;
   655 
   656     /**
   657      * Value of the {@link #MONTH} field indicating the
   658      * ninth month of the year in the Gregorian and Julian calendars.
   659      */
   660     public final static int SEPTEMBER = 8;
   661 
   662     /**
   663      * Value of the {@link #MONTH} field indicating the
   664      * tenth month of the year in the Gregorian and Julian calendars.
   665      */
   666     public final static int OCTOBER = 9;
   667 
   668     /**
   669      * Value of the {@link #MONTH} field indicating the
   670      * eleventh month of the year in the Gregorian and Julian calendars.
   671      */
   672     public final static int NOVEMBER = 10;
   673 
   674     /**
   675      * Value of the {@link #MONTH} field indicating the
   676      * twelfth month of the year in the Gregorian and Julian calendars.
   677      */
   678     public final static int DECEMBER = 11;
   679 
   680     /**
   681      * Value of the {@link #MONTH} field indicating the
   682      * thirteenth month of the year. Although <code>GregorianCalendar</code>
   683      * does not use this value, lunar calendars do.
   684      */
   685     public final static int UNDECIMBER = 12;
   686 
   687     /**
   688      * Value of the {@link #AM_PM} field indicating the
   689      * period of the day from midnight to just before noon.
   690      */
   691     public final static int AM = 0;
   692 
   693     /**
   694      * Value of the {@link #AM_PM} field indicating the
   695      * period of the day from noon to just before midnight.
   696      */
   697     public final static int PM = 1;
   698 
   699     /**
   700      * A style specifier for {@link #getDisplayNames(int, int, Locale)
   701      * getDisplayNames} indicating names in all styles, such as
   702      * "January" and "Jan".
   703      *
   704      * @see #SHORT
   705      * @see #LONG
   706      * @since 1.6
   707      */
   708     public static final int ALL_STYLES = 0;
   709 
   710     /**
   711      * A style specifier for {@link #getDisplayName(int, int, Locale)
   712      * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
   713      * getDisplayNames} indicating a short name, such as "Jan".
   714      *
   715      * @see #LONG
   716      * @since 1.6
   717      */
   718     public static final int SHORT = 1;
   719 
   720     /**
   721      * A style specifier for {@link #getDisplayName(int, int, Locale)
   722      * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
   723      * getDisplayNames} indicating a long name, such as "January".
   724      *
   725      * @see #SHORT
   726      * @since 1.6
   727      */
   728     public static final int LONG = 2;
   729 
   730     // Internal notes:
   731     // Calendar contains two kinds of time representations: current "time" in
   732     // milliseconds, and a set of calendar "fields" representing the current time.
   733     // The two representations are usually in sync, but can get out of sync
   734     // as follows.
   735     // 1. Initially, no fields are set, and the time is invalid.
   736     // 2. If the time is set, all fields are computed and in sync.
   737     // 3. If a single field is set, the time is invalid.
   738     // Recomputation of the time and fields happens when the object needs
   739     // to return a result to the user, or use a result for a computation.
   740 
   741     /**
   742      * The calendar field values for the currently set time for this calendar.
   743      * This is an array of <code>FIELD_COUNT</code> integers, with index values
   744      * <code>ERA</code> through <code>DST_OFFSET</code>.
   745      * @serial
   746      */
   747     protected int           fields[];
   748 
   749     /**
   750      * The flags which tell if a specified calendar field for the calendar is set.
   751      * A new object has no fields set.  After the first call to a method
   752      * which generates the fields, they all remain set after that.
   753      * This is an array of <code>FIELD_COUNT</code> booleans, with index values
   754      * <code>ERA</code> through <code>DST_OFFSET</code>.
   755      * @serial
   756      */
   757     protected boolean       isSet[];
   758 
   759     /**
   760      * Pseudo-time-stamps which specify when each field was set. There
   761      * are two special values, UNSET and COMPUTED. Values from
   762      * MINIMUM_USER_SET to Integer.MAX_VALUE are legal user set values.
   763      */
   764     transient private int   stamp[];
   765 
   766     /**
   767      * The currently set time for this calendar, expressed in milliseconds after
   768      * January 1, 1970, 0:00:00 GMT.
   769      * @see #isTimeSet
   770      * @serial
   771      */
   772     protected long          time;
   773 
   774     /**
   775      * True if then the value of <code>time</code> is valid.
   776      * The time is made invalid by a change to an item of <code>field[]</code>.
   777      * @see #time
   778      * @serial
   779      */
   780     protected boolean       isTimeSet;
   781 
   782     /**
   783      * True if <code>fields[]</code> are in sync with the currently set time.
   784      * If false, then the next attempt to get the value of a field will
   785      * force a recomputation of all fields from the current value of
   786      * <code>time</code>.
   787      * @serial
   788      */
   789     protected boolean       areFieldsSet;
   790 
   791     /**
   792      * True if all fields have been set.
   793      * @serial
   794      */
   795     transient boolean       areAllFieldsSet;
   796 
   797     /**
   798      * <code>True</code> if this calendar allows out-of-range field values during computation
   799      * of <code>time</code> from <code>fields[]</code>.
   800      * @see #setLenient
   801      * @see #isLenient
   802      * @serial
   803      */
   804     private boolean         lenient = true;
   805 
   806     /**
   807      * The <code>TimeZone</code> used by this calendar. <code>Calendar</code>
   808      * uses the time zone data to translate between locale and GMT time.
   809      * @serial
   810      */
   811     private TimeZone        zone;
   812 
   813     /**
   814      * <code>True</code> if zone references to a shared TimeZone object.
   815      */
   816     transient private boolean sharedZone = false;
   817 
   818     /**
   819      * The first day of the week, with possible values <code>SUNDAY</code>,
   820      * <code>MONDAY</code>, etc.  This is a locale-dependent value.
   821      * @serial
   822      */
   823     private int             firstDayOfWeek;
   824 
   825     /**
   826      * The number of days required for the first week in a month or year,
   827      * with possible values from 1 to 7.  This is a locale-dependent value.
   828      * @serial
   829      */
   830     private int             minimalDaysInFirstWeek;
   831 
   832     /**
   833      * Cache to hold the firstDayOfWeek and minimalDaysInFirstWeek
   834      * of a Locale.
   835      */
   836     private static final ConcurrentMap<Locale, int[]> cachedLocaleData
   837         = new ConcurrentHashMap<Locale, int[]>(3);
   838 
   839     // Special values of stamp[]
   840     /**
   841      * The corresponding fields[] has no value.
   842      */
   843     private static final int        UNSET = 0;
   844 
   845     /**
   846      * The value of the corresponding fields[] has been calculated internally.
   847      */
   848     private static final int        COMPUTED = 1;
   849 
   850     /**
   851      * The value of the corresponding fields[] has been set externally. Stamp
   852      * values which are greater than 1 represents the (pseudo) time when the
   853      * corresponding fields[] value was set.
   854      */
   855     private static final int        MINIMUM_USER_STAMP = 2;
   856 
   857     /**
   858      * The mask value that represents all of the fields.
   859      */
   860     static final int ALL_FIELDS = (1 << FIELD_COUNT) - 1;
   861 
   862     /**
   863      * The next available value for <code>stamp[]</code>, an internal array.
   864      * This actually should not be written out to the stream, and will probably
   865      * be removed from the stream in the near future.  In the meantime,
   866      * a value of <code>MINIMUM_USER_STAMP</code> should be used.
   867      * @serial
   868      */
   869     private int             nextStamp = MINIMUM_USER_STAMP;
   870 
   871     // the internal serial version which says which version was written
   872     // - 0 (default) for version up to JDK 1.1.5
   873     // - 1 for version from JDK 1.1.6, which writes a correct 'time' value
   874     //     as well as compatible values for other fields.  This is a
   875     //     transitional format.
   876     // - 2 (not implemented yet) a future version, in which fields[],
   877     //     areFieldsSet, and isTimeSet become transient, and isSet[] is
   878     //     removed. In JDK 1.1.6 we write a format compatible with version 2.
   879     static final int        currentSerialVersion = 1;
   880 
   881     /**
   882      * The version of the serialized data on the stream.  Possible values:
   883      * <dl>
   884      * <dt><b>0</b> or not present on stream</dt>
   885      * <dd>
   886      * JDK 1.1.5 or earlier.
   887      * </dd>
   888      * <dt><b>1</b></dt>
   889      * <dd>
   890      * JDK 1.1.6 or later.  Writes a correct 'time' value
   891      * as well as compatible values for other fields.  This is a
   892      * transitional format.
   893      * </dd>
   894      * </dl>
   895      * When streaming out this class, the most recent format
   896      * and the highest allowable <code>serialVersionOnStream</code>
   897      * is written.
   898      * @serial
   899      * @since JDK1.1.6
   900      */
   901     private int             serialVersionOnStream = currentSerialVersion;
   902 
   903     // Proclaim serialization compatibility with JDK 1.1
   904     static final long       serialVersionUID = -1807547505821590642L;
   905 
   906     // Mask values for calendar fields
   907     final static int ERA_MASK           = (1 << ERA);
   908     final static int YEAR_MASK          = (1 << YEAR);
   909     final static int MONTH_MASK         = (1 << MONTH);
   910     final static int WEEK_OF_YEAR_MASK  = (1 << WEEK_OF_YEAR);
   911     final static int WEEK_OF_MONTH_MASK = (1 << WEEK_OF_MONTH);
   912     final static int DAY_OF_MONTH_MASK  = (1 << DAY_OF_MONTH);
   913     final static int DATE_MASK          = DAY_OF_MONTH_MASK;
   914     final static int DAY_OF_YEAR_MASK   = (1 << DAY_OF_YEAR);
   915     final static int DAY_OF_WEEK_MASK   = (1 << DAY_OF_WEEK);
   916     final static int DAY_OF_WEEK_IN_MONTH_MASK  = (1 << DAY_OF_WEEK_IN_MONTH);
   917     final static int AM_PM_MASK         = (1 << AM_PM);
   918     final static int HOUR_MASK          = (1 << HOUR);
   919     final static int HOUR_OF_DAY_MASK   = (1 << HOUR_OF_DAY);
   920     final static int MINUTE_MASK        = (1 << MINUTE);
   921     final static int SECOND_MASK        = (1 << SECOND);
   922     final static int MILLISECOND_MASK   = (1 << MILLISECOND);
   923     final static int ZONE_OFFSET_MASK   = (1 << ZONE_OFFSET);
   924     final static int DST_OFFSET_MASK    = (1 << DST_OFFSET);
   925 
   926     /**
   927      * Constructs a Calendar with the default time zone
   928      * and locale.
   929      * @see     TimeZone#getDefault
   930      */
   931     protected Calendar()
   932     {
   933         this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
   934         sharedZone = true;
   935     }
   936 
   937     /**
   938      * Constructs a calendar with the specified time zone and locale.
   939      *
   940      * @param zone the time zone to use
   941      * @param aLocale the locale for the week data
   942      */
   943     protected Calendar(TimeZone zone, Locale aLocale)
   944     {
   945         fields = new int[FIELD_COUNT];
   946         isSet = new boolean[FIELD_COUNT];
   947         stamp = new int[FIELD_COUNT];
   948 
   949         this.zone = zone;
   950         setWeekCountData(aLocale);
   951     }
   952 
   953     /**
   954      * Gets a calendar using the default time zone and locale. The
   955      * <code>Calendar</code> returned is based on the current time
   956      * in the default time zone with the default locale.
   957      *
   958      * @return a Calendar.
   959      */
   960     public static Calendar getInstance()
   961     {
   962         Calendar cal = createCalendar(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
   963         cal.sharedZone = true;
   964         return cal;
   965     }
   966 
   967     /**
   968      * Gets a calendar using the specified time zone and default locale.
   969      * The <code>Calendar</code> returned is based on the current time
   970      * in the given time zone with the default locale.
   971      *
   972      * @param zone the time zone to use
   973      * @return a Calendar.
   974      */
   975     public static Calendar getInstance(TimeZone zone)
   976     {
   977         return createCalendar(zone, Locale.getDefault(Locale.Category.FORMAT));
   978     }
   979 
   980     /**
   981      * Gets a calendar using the default time zone and specified locale.
   982      * The <code>Calendar</code> returned is based on the current time
   983      * in the default time zone with the given locale.
   984      *
   985      * @param aLocale the locale for the week data
   986      * @return a Calendar.
   987      */
   988     public static Calendar getInstance(Locale aLocale)
   989     {
   990         Calendar cal = createCalendar(TimeZone.getDefaultRef(), aLocale);
   991         cal.sharedZone = true;
   992         return cal;
   993     }
   994 
   995     /**
   996      * Gets a calendar with the specified time zone and locale.
   997      * The <code>Calendar</code> returned is based on the current time
   998      * in the given time zone with the given locale.
   999      *
  1000      * @param zone the time zone to use
  1001      * @param aLocale the locale for the week data
  1002      * @return a Calendar.
  1003      */
  1004     public static Calendar getInstance(TimeZone zone,
  1005                                        Locale aLocale)
  1006     {
  1007         return createCalendar(zone, aLocale);
  1008     }
  1009 
  1010     private static Calendar createCalendar(TimeZone zone,
  1011                                            Locale aLocale)
  1012     {
  1013         Calendar cal = null;
  1014 
  1015         String caltype = aLocale.getUnicodeLocaleType("ca");
  1016         if (caltype == null) {
  1017             // Calendar type is not specified.
  1018             // If the specified locale is a Thai locale,
  1019             // returns a BuddhistCalendar instance.
  1020             if ("th".equals(aLocale.getLanguage())
  1021                     && ("TH".equals(aLocale.getCountry()))) {
  1022 //                cal = new BuddhistCalendar(zone, aLocale);
  1023             } else {
  1024 //                cal = new GregorianCalendar(zone, aLocale);
  1025             }
  1026         } else if (caltype.equals("japanese")) {
  1027 //            cal = new JapaneseImperialCalendar(zone, aLocale);
  1028         } else if (caltype.equals("buddhist")) {
  1029 //            cal = new BuddhistCalendar(zone, aLocale);
  1030         } else {
  1031             // Unsupported calendar type.
  1032             // Use Gregorian calendar as a fallback.
  1033 //            cal = new GregorianCalendar(zone, aLocale);
  1034         }
  1035 
  1036         return cal;
  1037     }
  1038 
  1039     /**
  1040      * Returns an array of all locales for which the <code>getInstance</code>
  1041      * methods of this class can return localized instances.
  1042      * The array returned must contain at least a <code>Locale</code>
  1043      * instance equal to {@link java.util.Locale#US Locale.US}.
  1044      *
  1045      * @return An array of locales for which localized
  1046      *         <code>Calendar</code> instances are available.
  1047      */
  1048     public static synchronized Locale[] getAvailableLocales()
  1049     {
  1050         return DateFormat.getAvailableLocales();
  1051     }
  1052 
  1053     /**
  1054      * Converts the current calendar field values in {@link #fields fields[]}
  1055      * to the millisecond time value
  1056      * {@link #time}.
  1057      *
  1058      * @see #complete()
  1059      * @see #computeFields()
  1060      */
  1061     protected abstract void computeTime();
  1062 
  1063     /**
  1064      * Converts the current millisecond time value {@link #time}
  1065      * to calendar field values in {@link #fields fields[]}.
  1066      * This allows you to sync up the calendar field values with
  1067      * a new time that is set for the calendar.  The time is <em>not</em>
  1068      * recomputed first; to recompute the time, then the fields, call the
  1069      * {@link #complete()} method.
  1070      *
  1071      * @see #computeTime()
  1072      */
  1073     protected abstract void computeFields();
  1074 
  1075     /**
  1076      * Returns a <code>Date</code> object representing this
  1077      * <code>Calendar</code>'s time value (millisecond offset from the <a
  1078      * href="#Epoch">Epoch</a>").
  1079      *
  1080      * @return a <code>Date</code> representing the time value.
  1081      * @see #setTime(Date)
  1082      * @see #getTimeInMillis()
  1083      */
  1084     public final Date getTime() {
  1085         return new Date(getTimeInMillis());
  1086     }
  1087 
  1088     /**
  1089      * Sets this Calendar's time with the given <code>Date</code>.
  1090      * <p>
  1091      * Note: Calling <code>setTime()</code> with
  1092      * <code>Date(Long.MAX_VALUE)</code> or <code>Date(Long.MIN_VALUE)</code>
  1093      * may yield incorrect field values from <code>get()</code>.
  1094      *
  1095      * @param date the given Date.
  1096      * @see #getTime()
  1097      * @see #setTimeInMillis(long)
  1098      */
  1099     public final void setTime(Date date) {
  1100         setTimeInMillis(date.getTime());
  1101     }
  1102 
  1103     /**
  1104      * Returns this Calendar's time value in milliseconds.
  1105      *
  1106      * @return the current time as UTC milliseconds from the epoch.
  1107      * @see #getTime()
  1108      * @see #setTimeInMillis(long)
  1109      */
  1110     public long getTimeInMillis() {
  1111         if (!isTimeSet) {
  1112             updateTime();
  1113         }
  1114         return time;
  1115     }
  1116 
  1117     /**
  1118      * Sets this Calendar's current time from the given long value.
  1119      *
  1120      * @param millis the new time in UTC milliseconds from the epoch.
  1121      * @see #setTime(Date)
  1122      * @see #getTimeInMillis()
  1123      */
  1124     public void setTimeInMillis(long millis) {
  1125         // If we don't need to recalculate the calendar field values,
  1126         // do nothing.
  1127 //        if (time == millis && isTimeSet && areFieldsSet && areAllFieldsSet
  1128 //            && (zone instanceof ZoneInfo) && !((ZoneInfo)zone).isDirty()) {
  1129 //            return;
  1130 //        }
  1131         time = millis;
  1132         isTimeSet = true;
  1133         areFieldsSet = false;
  1134         computeFields();
  1135         areAllFieldsSet = areFieldsSet = true;
  1136     }
  1137 
  1138     /**
  1139      * Returns the value of the given calendar field. In lenient mode,
  1140      * all calendar fields are normalized. In non-lenient mode, all
  1141      * calendar fields are validated and this method throws an
  1142      * exception if any calendar fields have out-of-range values. The
  1143      * normalization and validation are handled by the
  1144      * {@link #complete()} method, which process is calendar
  1145      * system dependent.
  1146      *
  1147      * @param field the given calendar field.
  1148      * @return the value for the given calendar field.
  1149      * @throws ArrayIndexOutOfBoundsException if the specified field is out of range
  1150      *             (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
  1151      * @see #set(int,int)
  1152      * @see #complete()
  1153      */
  1154     public int get(int field)
  1155     {
  1156         complete();
  1157         return internalGet(field);
  1158     }
  1159 
  1160     /**
  1161      * Returns the value of the given calendar field. This method does
  1162      * not involve normalization or validation of the field value.
  1163      *
  1164      * @param field the given calendar field.
  1165      * @return the value for the given calendar field.
  1166      * @see #get(int)
  1167      */
  1168     protected final int internalGet(int field)
  1169     {
  1170         return fields[field];
  1171     }
  1172 
  1173     /**
  1174      * Sets the value of the given calendar field. This method does
  1175      * not affect any setting state of the field in this
  1176      * <code>Calendar</code> instance.
  1177      *
  1178      * @throws IndexOutOfBoundsException if the specified field is out of range
  1179      *             (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
  1180      * @see #areFieldsSet
  1181      * @see #isTimeSet
  1182      * @see #areAllFieldsSet
  1183      * @see #set(int,int)
  1184      */
  1185     final void internalSet(int field, int value)
  1186     {
  1187         fields[field] = value;
  1188     }
  1189 
  1190     /**
  1191      * Sets the given calendar field to the given value. The value is not
  1192      * interpreted by this method regardless of the leniency mode.
  1193      *
  1194      * @param field the given calendar field.
  1195      * @param value the value to be set for the given calendar field.
  1196      * @throws ArrayIndexOutOfBoundsException if the specified field is out of range
  1197      *             (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
  1198      * in non-lenient mode.
  1199      * @see #set(int,int,int)
  1200      * @see #set(int,int,int,int,int)
  1201      * @see #set(int,int,int,int,int,int)
  1202      * @see #get(int)
  1203      */
  1204     public void set(int field, int value)
  1205     {
  1206         // If the fields are partially normalized, calculate all the
  1207         // fields before changing any fields.
  1208         if (areFieldsSet && !areAllFieldsSet) {
  1209             computeFields();
  1210         }
  1211         internalSet(field, value);
  1212         isTimeSet = false;
  1213         areFieldsSet = false;
  1214         isSet[field] = true;
  1215         stamp[field] = nextStamp++;
  1216         if (nextStamp == Integer.MAX_VALUE) {
  1217             adjustStamp();
  1218         }
  1219     }
  1220 
  1221     /**
  1222      * Sets the values for the calendar fields <code>YEAR</code>,
  1223      * <code>MONTH</code>, and <code>DAY_OF_MONTH</code>.
  1224      * Previous values of other calendar fields are retained.  If this is not desired,
  1225      * call {@link #clear()} first.
  1226      *
  1227      * @param year the value used to set the <code>YEAR</code> calendar field.
  1228      * @param month the value used to set the <code>MONTH</code> calendar field.
  1229      * Month value is 0-based. e.g., 0 for January.
  1230      * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
  1231      * @see #set(int,int)
  1232      * @see #set(int,int,int,int,int)
  1233      * @see #set(int,int,int,int,int,int)
  1234      */
  1235     public final void set(int year, int month, int date)
  1236     {
  1237         set(YEAR, year);
  1238         set(MONTH, month);
  1239         set(DATE, date);
  1240     }
  1241 
  1242     /**
  1243      * Sets the values for the calendar fields <code>YEAR</code>,
  1244      * <code>MONTH</code>, <code>DAY_OF_MONTH</code>,
  1245      * <code>HOUR_OF_DAY</code>, and <code>MINUTE</code>.
  1246      * Previous values of other fields are retained.  If this is not desired,
  1247      * call {@link #clear()} first.
  1248      *
  1249      * @param year the value used to set the <code>YEAR</code> calendar field.
  1250      * @param month the value used to set the <code>MONTH</code> calendar field.
  1251      * Month value is 0-based. e.g., 0 for January.
  1252      * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
  1253      * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field.
  1254      * @param minute the value used to set the <code>MINUTE</code> calendar field.
  1255      * @see #set(int,int)
  1256      * @see #set(int,int,int)
  1257      * @see #set(int,int,int,int,int,int)
  1258      */
  1259     public final void set(int year, int month, int date, int hourOfDay, int minute)
  1260     {
  1261         set(YEAR, year);
  1262         set(MONTH, month);
  1263         set(DATE, date);
  1264         set(HOUR_OF_DAY, hourOfDay);
  1265         set(MINUTE, minute);
  1266     }
  1267 
  1268     /**
  1269      * Sets the values for the fields <code>YEAR</code>, <code>MONTH</code>,
  1270      * <code>DAY_OF_MONTH</code>, <code>HOUR</code>, <code>MINUTE</code>, and
  1271      * <code>SECOND</code>.
  1272      * Previous values of other fields are retained.  If this is not desired,
  1273      * call {@link #clear()} first.
  1274      *
  1275      * @param year the value used to set the <code>YEAR</code> calendar field.
  1276      * @param month the value used to set the <code>MONTH</code> calendar field.
  1277      * Month value is 0-based. e.g., 0 for January.
  1278      * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
  1279      * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field.
  1280      * @param minute the value used to set the <code>MINUTE</code> calendar field.
  1281      * @param second the value used to set the <code>SECOND</code> calendar field.
  1282      * @see #set(int,int)
  1283      * @see #set(int,int,int)
  1284      * @see #set(int,int,int,int,int)
  1285      */
  1286     public final void set(int year, int month, int date, int hourOfDay, int minute,
  1287                           int second)
  1288     {
  1289         set(YEAR, year);
  1290         set(MONTH, month);
  1291         set(DATE, date);
  1292         set(HOUR_OF_DAY, hourOfDay);
  1293         set(MINUTE, minute);
  1294         set(SECOND, second);
  1295     }
  1296 
  1297     /**
  1298      * Sets all the calendar field values and the time value
  1299      * (millisecond offset from the <a href="#Epoch">Epoch</a>) of
  1300      * this <code>Calendar</code> undefined. This means that {@link
  1301      * #isSet(int) isSet()} will return <code>false</code> for all the
  1302      * calendar fields, and the date and time calculations will treat
  1303      * the fields as if they had never been set. A
  1304      * <code>Calendar</code> implementation class may use its specific
  1305      * default field values for date/time calculations. For example,
  1306      * <code>GregorianCalendar</code> uses 1970 if the
  1307      * <code>YEAR</code> field value is undefined.
  1308      *
  1309      * @see #clear(int)
  1310      */
  1311     public final void clear()
  1312     {
  1313         for (int i = 0; i < fields.length; ) {
  1314             stamp[i] = fields[i] = 0; // UNSET == 0
  1315             isSet[i++] = false;
  1316         }
  1317         areAllFieldsSet = areFieldsSet = false;
  1318         isTimeSet = false;
  1319     }
  1320 
  1321     /**
  1322      * Sets the given calendar field value and the time value
  1323      * (millisecond offset from the <a href="#Epoch">Epoch</a>) of
  1324      * this <code>Calendar</code> undefined. This means that {@link
  1325      * #isSet(int) isSet(field)} will return <code>false</code>, and
  1326      * the date and time calculations will treat the field as if it
  1327      * had never been set. A <code>Calendar</code> implementation
  1328      * class may use the field's specific default value for date and
  1329      * time calculations.
  1330      *
  1331      * <p>The {@link #HOUR_OF_DAY}, {@link #HOUR} and {@link #AM_PM}
  1332      * fields are handled independently and the <a
  1333      * href="#time_resolution">the resolution rule for the time of
  1334      * day</a> is applied. Clearing one of the fields doesn't reset
  1335      * the hour of day value of this <code>Calendar</code>. Use {@link
  1336      * #set(int,int) set(Calendar.HOUR_OF_DAY, 0)} to reset the hour
  1337      * value.
  1338      *
  1339      * @param field the calendar field to be cleared.
  1340      * @see #clear()
  1341      */
  1342     public final void clear(int field)
  1343     {
  1344         fields[field] = 0;
  1345         stamp[field] = UNSET;
  1346         isSet[field] = false;
  1347 
  1348         areAllFieldsSet = areFieldsSet = false;
  1349         isTimeSet = false;
  1350     }
  1351 
  1352     /**
  1353      * Determines if the given calendar field has a value set,
  1354      * including cases that the value has been set by internal fields
  1355      * calculations triggered by a <code>get</code> method call.
  1356      *
  1357      * @return <code>true</code> if the given calendar field has a value set;
  1358      * <code>false</code> otherwise.
  1359      */
  1360     public final boolean isSet(int field)
  1361     {
  1362         return stamp[field] != UNSET;
  1363     }
  1364 
  1365     /**
  1366      * Returns the string representation of the calendar
  1367      * <code>field</code> value in the given <code>style</code> and
  1368      * <code>locale</code>.  If no string representation is
  1369      * applicable, <code>null</code> is returned. This method calls
  1370      * {@link Calendar#get(int) get(field)} to get the calendar
  1371      * <code>field</code> value if the string representation is
  1372      * applicable to the given calendar <code>field</code>.
  1373      *
  1374      * <p>For example, if this <code>Calendar</code> is a
  1375      * <code>GregorianCalendar</code> and its date is 2005-01-01, then
  1376      * the string representation of the {@link #MONTH} field would be
  1377      * "January" in the long style in an English locale or "Jan" in
  1378      * the short style. However, no string representation would be
  1379      * available for the {@link #DAY_OF_MONTH} field, and this method
  1380      * would return <code>null</code>.
  1381      *
  1382      * <p>The default implementation supports the calendar fields for
  1383      * which a {@link DateFormatSymbols} has names in the given
  1384      * <code>locale</code>.
  1385      *
  1386      * @param field
  1387      *        the calendar field for which the string representation
  1388      *        is returned
  1389      * @param style
  1390      *        the style applied to the string representation; one of
  1391      *        {@link #SHORT} or {@link #LONG}.
  1392      * @param locale
  1393      *        the locale for the string representation
  1394      * @return the string representation of the given
  1395      *        <code>field</code> in the given <code>style</code>, or
  1396      *        <code>null</code> if no string representation is
  1397      *        applicable.
  1398      * @exception IllegalArgumentException
  1399      *        if <code>field</code> or <code>style</code> is invalid,
  1400      *        or if this <code>Calendar</code> is non-lenient and any
  1401      *        of the calendar fields have invalid values
  1402      * @exception NullPointerException
  1403      *        if <code>locale</code> is null
  1404      * @since 1.6
  1405      */
  1406     public String getDisplayName(int field, int style, Locale locale) {
  1407         if (!checkDisplayNameParams(field, style, ALL_STYLES, LONG, locale,
  1408                                     ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
  1409             return null;
  1410         }
  1411 
  1412         DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
  1413         String[] strings = getFieldStrings(field, style, symbols);
  1414         if (strings != null) {
  1415             int fieldValue = get(field);
  1416             if (fieldValue < strings.length) {
  1417                 return strings[fieldValue];
  1418             }
  1419         }
  1420         return null;
  1421     }
  1422 
  1423     /**
  1424      * Returns a <code>Map</code> containing all names of the calendar
  1425      * <code>field</code> in the given <code>style</code> and
  1426      * <code>locale</code> and their corresponding field values. For
  1427      * example, if this <code>Calendar</code> is a {@link
  1428      * GregorianCalendar}, the returned map would contain "Jan" to
  1429      * {@link #JANUARY}, "Feb" to {@link #FEBRUARY}, and so on, in the
  1430      * {@linkplain #SHORT short} style in an English locale.
  1431      *
  1432      * <p>The values of other calendar fields may be taken into
  1433      * account to determine a set of display names. For example, if
  1434      * this <code>Calendar</code> is a lunisolar calendar system and
  1435      * the year value given by the {@link #YEAR} field has a leap
  1436      * month, this method would return month names containing the leap
  1437      * month name, and month names are mapped to their values specific
  1438      * for the year.
  1439      *
  1440      * <p>The default implementation supports display names contained in
  1441      * a {@link DateFormatSymbols}. For example, if <code>field</code>
  1442      * is {@link #MONTH} and <code>style</code> is {@link
  1443      * #ALL_STYLES}, this method returns a <code>Map</code> containing
  1444      * all strings returned by {@link DateFormatSymbols#getShortMonths()}
  1445      * and {@link DateFormatSymbols#getMonths()}.
  1446      *
  1447      * @param field
  1448      *        the calendar field for which the display names are returned
  1449      * @param style
  1450      *        the style applied to the display names; one of {@link
  1451      *        #SHORT}, {@link #LONG}, or {@link #ALL_STYLES}.
  1452      * @param locale
  1453      *        the locale for the display names
  1454      * @return a <code>Map</code> containing all display names in
  1455      *        <code>style</code> and <code>locale</code> and their
  1456      *        field values, or <code>null</code> if no display names
  1457      *        are defined for <code>field</code>
  1458      * @exception IllegalArgumentException
  1459      *        if <code>field</code> or <code>style</code> is invalid,
  1460      *        or if this <code>Calendar</code> is non-lenient and any
  1461      *        of the calendar fields have invalid values
  1462      * @exception NullPointerException
  1463      *        if <code>locale</code> is null
  1464      * @since 1.6
  1465      */
  1466     public Map<String, Integer> getDisplayNames(int field, int style, Locale locale) {
  1467         if (!checkDisplayNameParams(field, style, ALL_STYLES, LONG, locale,
  1468                                     ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
  1469             return null;
  1470         }
  1471 
  1472         // ALL_STYLES
  1473         if (style == ALL_STYLES) {
  1474             Map<String,Integer> shortNames = getDisplayNamesImpl(field, SHORT, locale);
  1475             if (field == ERA || field == AM_PM) {
  1476                 return shortNames;
  1477             }
  1478             Map<String,Integer> longNames = getDisplayNamesImpl(field, LONG, locale);
  1479             if (shortNames == null) {
  1480                 return longNames;
  1481             }
  1482             if (longNames != null) {
  1483                 shortNames.putAll(longNames);
  1484             }
  1485             return shortNames;
  1486         }
  1487 
  1488         // SHORT or LONG
  1489         return getDisplayNamesImpl(field, style, locale);
  1490     }
  1491 
  1492     private Map<String,Integer> getDisplayNamesImpl(int field, int style, Locale locale) {
  1493         DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
  1494         String[] strings = getFieldStrings(field, style, symbols);
  1495         if (strings != null) {
  1496             Map<String,Integer> names = new HashMap<String,Integer>();
  1497             for (int i = 0; i < strings.length; i++) {
  1498                 if (strings[i].length() == 0) {
  1499                     continue;
  1500                 }
  1501                 names.put(strings[i], i);
  1502             }
  1503             return names;
  1504         }
  1505         return null;
  1506     }
  1507 
  1508     boolean checkDisplayNameParams(int field, int style, int minStyle, int maxStyle,
  1509                                    Locale locale, int fieldMask) {
  1510         if (field < 0 || field >= fields.length ||
  1511             style < minStyle || style > maxStyle) {
  1512             throw new IllegalArgumentException();
  1513         }
  1514         if (locale == null) {
  1515             throw new NullPointerException();
  1516         }
  1517         return isFieldSet(fieldMask, field);
  1518     }
  1519 
  1520     private String[] getFieldStrings(int field, int style, DateFormatSymbols symbols) {
  1521         String[] strings = null;
  1522         switch (field) {
  1523         case ERA:
  1524             strings = symbols.getEras();
  1525             break;
  1526 
  1527         case MONTH:
  1528             strings = (style == LONG) ? symbols.getMonths() : symbols.getShortMonths();
  1529             break;
  1530 
  1531         case DAY_OF_WEEK:
  1532             strings = (style == LONG) ? symbols.getWeekdays() : symbols.getShortWeekdays();
  1533             break;
  1534 
  1535         case AM_PM:
  1536             strings = symbols.getAmPmStrings();
  1537             break;
  1538         }
  1539         return strings;
  1540     }
  1541 
  1542     /**
  1543      * Fills in any unset fields in the calendar fields. First, the {@link
  1544      * #computeTime()} method is called if the time value (millisecond offset
  1545      * from the <a href="#Epoch">Epoch</a>) has not been calculated from
  1546      * calendar field values. Then, the {@link #computeFields()} method is
  1547      * called to calculate all calendar field values.
  1548      */
  1549     protected void complete()
  1550     {
  1551         if (!isTimeSet)
  1552             updateTime();
  1553         if (!areFieldsSet || !areAllFieldsSet) {
  1554             computeFields(); // fills in unset fields
  1555             areAllFieldsSet = areFieldsSet = true;
  1556         }
  1557     }
  1558 
  1559     /**
  1560      * Returns whether the value of the specified calendar field has been set
  1561      * externally by calling one of the setter methods rather than by the
  1562      * internal time calculation.
  1563      *
  1564      * @return <code>true</code> if the field has been set externally,
  1565      * <code>false</code> otherwise.
  1566      * @exception IndexOutOfBoundsException if the specified
  1567      *                <code>field</code> is out of range
  1568      *               (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
  1569      * @see #selectFields()
  1570      * @see #setFieldsComputed(int)
  1571      */
  1572     final boolean isExternallySet(int field) {
  1573         return stamp[field] >= MINIMUM_USER_STAMP;
  1574     }
  1575 
  1576     /**
  1577      * Returns a field mask (bit mask) indicating all calendar fields that
  1578      * have the state of externally or internally set.
  1579      *
  1580      * @return a bit mask indicating set state fields
  1581      */
  1582     final int getSetStateFields() {
  1583         int mask = 0;
  1584         for (int i = 0; i < fields.length; i++) {
  1585             if (stamp[i] != UNSET) {
  1586                 mask |= 1 << i;
  1587             }
  1588         }
  1589         return mask;
  1590     }
  1591 
  1592     /**
  1593      * Sets the state of the specified calendar fields to
  1594      * <em>computed</em>. This state means that the specified calendar fields
  1595      * have valid values that have been set by internal time calculation
  1596      * rather than by calling one of the setter methods.
  1597      *
  1598      * @param fieldMask the field to be marked as computed.
  1599      * @exception IndexOutOfBoundsException if the specified
  1600      *                <code>field</code> is out of range
  1601      *               (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
  1602      * @see #isExternallySet(int)
  1603      * @see #selectFields()
  1604      */
  1605     final void setFieldsComputed(int fieldMask) {
  1606         if (fieldMask == ALL_FIELDS) {
  1607             for (int i = 0; i < fields.length; i++) {
  1608                 stamp[i] = COMPUTED;
  1609                 isSet[i] = true;
  1610             }
  1611             areFieldsSet = areAllFieldsSet = true;
  1612         } else {
  1613             for (int i = 0; i < fields.length; i++) {
  1614                 if ((fieldMask & 1) == 1) {
  1615                     stamp[i] = COMPUTED;
  1616                     isSet[i] = true;
  1617                 } else {
  1618                     if (areAllFieldsSet && !isSet[i]) {
  1619                         areAllFieldsSet = false;
  1620                     }
  1621                 }
  1622                 fieldMask >>>= 1;
  1623             }
  1624         }
  1625     }
  1626 
  1627     /**
  1628      * Sets the state of the calendar fields that are <em>not</em> specified
  1629      * by <code>fieldMask</code> to <em>unset</em>. If <code>fieldMask</code>
  1630      * specifies all the calendar fields, then the state of this
  1631      * <code>Calendar</code> becomes that all the calendar fields are in sync
  1632      * with the time value (millisecond offset from the Epoch).
  1633      *
  1634      * @param fieldMask the field mask indicating which calendar fields are in
  1635      * sync with the time value.
  1636      * @exception IndexOutOfBoundsException if the specified
  1637      *                <code>field</code> is out of range
  1638      *               (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
  1639      * @see #isExternallySet(int)
  1640      * @see #selectFields()
  1641      */
  1642     final void setFieldsNormalized(int fieldMask) {
  1643         if (fieldMask != ALL_FIELDS) {
  1644             for (int i = 0; i < fields.length; i++) {
  1645                 if ((fieldMask & 1) == 0) {
  1646                     stamp[i] = fields[i] = 0; // UNSET == 0
  1647                     isSet[i] = false;
  1648                 }
  1649                 fieldMask >>= 1;
  1650             }
  1651         }
  1652 
  1653         // Some or all of the fields are in sync with the
  1654         // milliseconds, but the stamp values are not normalized yet.
  1655         areFieldsSet = true;
  1656         areAllFieldsSet = false;
  1657     }
  1658 
  1659     /**
  1660      * Returns whether the calendar fields are partially in sync with the time
  1661      * value or fully in sync but not stamp values are not normalized yet.
  1662      */
  1663     final boolean isPartiallyNormalized() {
  1664         return areFieldsSet && !areAllFieldsSet;
  1665     }
  1666 
  1667     /**
  1668      * Returns whether the calendar fields are fully in sync with the time
  1669      * value.
  1670      */
  1671     final boolean isFullyNormalized() {
  1672         return areFieldsSet && areAllFieldsSet;
  1673     }
  1674 
  1675     /**
  1676      * Marks this Calendar as not sync'd.
  1677      */
  1678     final void setUnnormalized() {
  1679         areFieldsSet = areAllFieldsSet = false;
  1680     }
  1681 
  1682     /**
  1683      * Returns whether the specified <code>field</code> is on in the
  1684      * <code>fieldMask</code>.
  1685      */
  1686     static final boolean isFieldSet(int fieldMask, int field) {
  1687         return (fieldMask & (1 << field)) != 0;
  1688     }
  1689 
  1690     /**
  1691      * Returns a field mask indicating which calendar field values
  1692      * to be used to calculate the time value. The calendar fields are
  1693      * returned as a bit mask, each bit of which corresponds to a field, i.e.,
  1694      * the mask value of <code>field</code> is <code>(1 &lt;&lt;
  1695      * field)</code>. For example, 0x26 represents the <code>YEAR</code>,
  1696      * <code>MONTH</code>, and <code>DAY_OF_MONTH</code> fields (i.e., 0x26 is
  1697      * equal to
  1698      * <code>(1&lt;&lt;YEAR)|(1&lt;&lt;MONTH)|(1&lt;&lt;DAY_OF_MONTH))</code>.
  1699      *
  1700      * <p>This method supports the calendar fields resolution as described in
  1701      * the class description. If the bit mask for a given field is on and its
  1702      * field has not been set (i.e., <code>isSet(field)</code> is
  1703      * <code>false</code>), then the default value of the field has to be
  1704      * used, which case means that the field has been selected because the
  1705      * selected combination involves the field.
  1706      *
  1707      * @return a bit mask of selected fields
  1708      * @see #isExternallySet(int)
  1709      * @see #setInternallySetState(int)
  1710      */
  1711     final int selectFields() {
  1712         // This implementation has been taken from the GregorianCalendar class.
  1713 
  1714         // The YEAR field must always be used regardless of its SET
  1715         // state because YEAR is a mandatory field to determine the date
  1716         // and the default value (EPOCH_YEAR) may change through the
  1717         // normalization process.
  1718         int fieldMask = YEAR_MASK;
  1719 
  1720         if (stamp[ERA] != UNSET) {
  1721             fieldMask |= ERA_MASK;
  1722         }
  1723         // Find the most recent group of fields specifying the day within
  1724         // the year.  These may be any of the following combinations:
  1725         //   MONTH + DAY_OF_MONTH
  1726         //   MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
  1727         //   MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
  1728         //   DAY_OF_YEAR
  1729         //   WEEK_OF_YEAR + DAY_OF_WEEK
  1730         // We look for the most recent of the fields in each group to determine
  1731         // the age of the group.  For groups involving a week-related field such
  1732         // as WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR, both the
  1733         // week-related field and the DAY_OF_WEEK must be set for the group as a
  1734         // whole to be considered.  (See bug 4153860 - liu 7/24/98.)
  1735         int dowStamp = stamp[DAY_OF_WEEK];
  1736         int monthStamp = stamp[MONTH];
  1737         int domStamp = stamp[DAY_OF_MONTH];
  1738         int womStamp = aggregateStamp(stamp[WEEK_OF_MONTH], dowStamp);
  1739         int dowimStamp = aggregateStamp(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
  1740         int doyStamp = stamp[DAY_OF_YEAR];
  1741         int woyStamp = aggregateStamp(stamp[WEEK_OF_YEAR], dowStamp);
  1742 
  1743         int bestStamp = domStamp;
  1744         if (womStamp > bestStamp) {
  1745             bestStamp = womStamp;
  1746         }
  1747         if (dowimStamp > bestStamp) {
  1748             bestStamp = dowimStamp;
  1749         }
  1750         if (doyStamp > bestStamp) {
  1751             bestStamp = doyStamp;
  1752         }
  1753         if (woyStamp > bestStamp) {
  1754             bestStamp = woyStamp;
  1755         }
  1756 
  1757         /* No complete combination exists.  Look for WEEK_OF_MONTH,
  1758          * DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR alone.  Treat DAY_OF_WEEK alone
  1759          * as DAY_OF_WEEK_IN_MONTH.
  1760          */
  1761         if (bestStamp == UNSET) {
  1762             womStamp = stamp[WEEK_OF_MONTH];
  1763             dowimStamp = Math.max(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
  1764             woyStamp = stamp[WEEK_OF_YEAR];
  1765             bestStamp = Math.max(Math.max(womStamp, dowimStamp), woyStamp);
  1766 
  1767             /* Treat MONTH alone or no fields at all as DAY_OF_MONTH.  This may
  1768              * result in bestStamp = domStamp = UNSET if no fields are set,
  1769              * which indicates DAY_OF_MONTH.
  1770              */
  1771             if (bestStamp == UNSET) {
  1772                 bestStamp = domStamp = monthStamp;
  1773             }
  1774         }
  1775 
  1776         if (bestStamp == domStamp ||
  1777            (bestStamp == womStamp && stamp[WEEK_OF_MONTH] >= stamp[WEEK_OF_YEAR]) ||
  1778            (bestStamp == dowimStamp && stamp[DAY_OF_WEEK_IN_MONTH] >= stamp[WEEK_OF_YEAR])) {
  1779             fieldMask |= MONTH_MASK;
  1780             if (bestStamp == domStamp) {
  1781                 fieldMask |= DAY_OF_MONTH_MASK;
  1782             } else {
  1783                 assert (bestStamp == womStamp || bestStamp == dowimStamp);
  1784                 if (dowStamp != UNSET) {
  1785                     fieldMask |= DAY_OF_WEEK_MASK;
  1786                 }
  1787                 if (womStamp == dowimStamp) {
  1788                     // When they are equal, give the priority to
  1789                     // WEEK_OF_MONTH for compatibility.
  1790                     if (stamp[WEEK_OF_MONTH] >= stamp[DAY_OF_WEEK_IN_MONTH]) {
  1791                         fieldMask |= WEEK_OF_MONTH_MASK;
  1792                     } else {
  1793                         fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;
  1794                     }
  1795                 } else {
  1796                     if (bestStamp == womStamp) {
  1797                         fieldMask |= WEEK_OF_MONTH_MASK;
  1798                     } else {
  1799                         assert (bestStamp == dowimStamp);
  1800                         if (stamp[DAY_OF_WEEK_IN_MONTH] != UNSET) {
  1801                             fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;
  1802                         }
  1803                     }
  1804                 }
  1805             }
  1806         } else {
  1807             assert (bestStamp == doyStamp || bestStamp == woyStamp ||
  1808                     bestStamp == UNSET);
  1809             if (bestStamp == doyStamp) {
  1810                 fieldMask |= DAY_OF_YEAR_MASK;
  1811             } else {
  1812                 assert (bestStamp == woyStamp);
  1813                 if (dowStamp != UNSET) {
  1814                     fieldMask |= DAY_OF_WEEK_MASK;
  1815                 }
  1816                 fieldMask |= WEEK_OF_YEAR_MASK;
  1817             }
  1818         }
  1819 
  1820         // Find the best set of fields specifying the time of day.  There
  1821         // are only two possibilities here; the HOUR_OF_DAY or the
  1822         // AM_PM and the HOUR.
  1823         int hourOfDayStamp = stamp[HOUR_OF_DAY];
  1824         int hourStamp = aggregateStamp(stamp[HOUR], stamp[AM_PM]);
  1825         bestStamp = (hourStamp > hourOfDayStamp) ? hourStamp : hourOfDayStamp;
  1826 
  1827         // if bestStamp is still UNSET, then take HOUR or AM_PM. (See 4846659)
  1828         if (bestStamp == UNSET) {
  1829             bestStamp = Math.max(stamp[HOUR], stamp[AM_PM]);
  1830         }
  1831 
  1832         // Hours
  1833         if (bestStamp != UNSET) {
  1834             if (bestStamp == hourOfDayStamp) {
  1835                 fieldMask |= HOUR_OF_DAY_MASK;
  1836             } else {
  1837                 fieldMask |= HOUR_MASK;
  1838                 if (stamp[AM_PM] != UNSET) {
  1839                     fieldMask |= AM_PM_MASK;
  1840                 }
  1841             }
  1842         }
  1843         if (stamp[MINUTE] != UNSET) {
  1844             fieldMask |= MINUTE_MASK;
  1845         }
  1846         if (stamp[SECOND] != UNSET) {
  1847             fieldMask |= SECOND_MASK;
  1848         }
  1849         if (stamp[MILLISECOND] != UNSET) {
  1850             fieldMask |= MILLISECOND_MASK;
  1851         }
  1852         if (stamp[ZONE_OFFSET] >= MINIMUM_USER_STAMP) {
  1853                 fieldMask |= ZONE_OFFSET_MASK;
  1854         }
  1855         if (stamp[DST_OFFSET] >= MINIMUM_USER_STAMP) {
  1856             fieldMask |= DST_OFFSET_MASK;
  1857         }
  1858 
  1859         return fieldMask;
  1860     }
  1861 
  1862     /**
  1863      * Returns the pseudo-time-stamp for two fields, given their
  1864      * individual pseudo-time-stamps.  If either of the fields
  1865      * is unset, then the aggregate is unset.  Otherwise, the
  1866      * aggregate is the later of the two stamps.
  1867      */
  1868     private static final int aggregateStamp(int stamp_a, int stamp_b) {
  1869         if (stamp_a == UNSET || stamp_b == UNSET) {
  1870             return UNSET;
  1871         }
  1872         return (stamp_a > stamp_b) ? stamp_a : stamp_b;
  1873     }
  1874 
  1875     /**
  1876      * Compares this <code>Calendar</code> to the specified
  1877      * <code>Object</code>.  The result is <code>true</code> if and only if
  1878      * the argument is a <code>Calendar</code> object of the same calendar
  1879      * system that represents the same time value (millisecond offset from the
  1880      * <a href="#Epoch">Epoch</a>) under the same
  1881      * <code>Calendar</code> parameters as this object.
  1882      *
  1883      * <p>The <code>Calendar</code> parameters are the values represented
  1884      * by the <code>isLenient</code>, <code>getFirstDayOfWeek</code>,
  1885      * <code>getMinimalDaysInFirstWeek</code> and <code>getTimeZone</code>
  1886      * methods. If there is any difference in those parameters
  1887      * between the two <code>Calendar</code>s, this method returns
  1888      * <code>false</code>.
  1889      *
  1890      * <p>Use the {@link #compareTo(Calendar) compareTo} method to
  1891      * compare only the time values.
  1892      *
  1893      * @param obj the object to compare with.
  1894      * @return <code>true</code> if this object is equal to <code>obj</code>;
  1895      * <code>false</code> otherwise.
  1896      */
  1897     public boolean equals(Object obj) {
  1898         if (this == obj)
  1899             return true;
  1900         try {
  1901             Calendar that = (Calendar)obj;
  1902             return compareTo(getMillisOf(that)) == 0 &&
  1903                 lenient == that.lenient &&
  1904                 firstDayOfWeek == that.firstDayOfWeek &&
  1905                 minimalDaysInFirstWeek == that.minimalDaysInFirstWeek &&
  1906                 zone.equals(that.zone);
  1907         } catch (Exception e) {
  1908             // Note: GregorianCalendar.computeTime throws
  1909             // IllegalArgumentException if the ERA value is invalid
  1910             // even it's in lenient mode.
  1911         }
  1912         return false;
  1913     }
  1914 
  1915     /**
  1916      * Returns a hash code for this calendar.
  1917      *
  1918      * @return a hash code value for this object.
  1919      * @since 1.2
  1920      */
  1921     public int hashCode() {
  1922         // 'otheritems' represents the hash code for the previous versions.
  1923         int otheritems = (lenient ? 1 : 0)
  1924             | (firstDayOfWeek << 1)
  1925             | (minimalDaysInFirstWeek << 4)
  1926             | (zone.hashCode() << 7);
  1927         long t = getMillisOf(this);
  1928         return (int) t ^ (int)(t >> 32) ^ otheritems;
  1929     }
  1930 
  1931     /**
  1932      * Returns whether this <code>Calendar</code> represents a time
  1933      * before the time represented by the specified
  1934      * <code>Object</code>. This method is equivalent to:
  1935      * <pre><blockquote>
  1936      *         compareTo(when) < 0
  1937      * </blockquote></pre>
  1938      * if and only if <code>when</code> is a <code>Calendar</code>
  1939      * instance. Otherwise, the method returns <code>false</code>.
  1940      *
  1941      * @param when the <code>Object</code> to be compared
  1942      * @return <code>true</code> if the time of this
  1943      * <code>Calendar</code> is before the time represented by
  1944      * <code>when</code>; <code>false</code> otherwise.
  1945      * @see     #compareTo(Calendar)
  1946      */
  1947     public boolean before(Object when) {
  1948         return when instanceof Calendar
  1949             && compareTo((Calendar)when) < 0;
  1950     }
  1951 
  1952     /**
  1953      * Returns whether this <code>Calendar</code> represents a time
  1954      * after the time represented by the specified
  1955      * <code>Object</code>. This method is equivalent to:
  1956      * <pre><blockquote>
  1957      *         compareTo(when) > 0
  1958      * </blockquote></pre>
  1959      * if and only if <code>when</code> is a <code>Calendar</code>
  1960      * instance. Otherwise, the method returns <code>false</code>.
  1961      *
  1962      * @param when the <code>Object</code> to be compared
  1963      * @return <code>true</code> if the time of this <code>Calendar</code> is
  1964      * after the time represented by <code>when</code>; <code>false</code>
  1965      * otherwise.
  1966      * @see     #compareTo(Calendar)
  1967      */
  1968     public boolean after(Object when) {
  1969         return when instanceof Calendar
  1970             && compareTo((Calendar)when) > 0;
  1971     }
  1972 
  1973     /**
  1974      * Compares the time values (millisecond offsets from the <a
  1975      * href="#Epoch">Epoch</a>) represented by two
  1976      * <code>Calendar</code> objects.
  1977      *
  1978      * @param anotherCalendar the <code>Calendar</code> to be compared.
  1979      * @return the value <code>0</code> if the time represented by the argument
  1980      * is equal to the time represented by this <code>Calendar</code>; a value
  1981      * less than <code>0</code> if the time of this <code>Calendar</code> is
  1982      * before the time represented by the argument; and a value greater than
  1983      * <code>0</code> if the time of this <code>Calendar</code> is after the
  1984      * time represented by the argument.
  1985      * @exception NullPointerException if the specified <code>Calendar</code> is
  1986      *            <code>null</code>.
  1987      * @exception IllegalArgumentException if the time value of the
  1988      * specified <code>Calendar</code> object can't be obtained due to
  1989      * any invalid calendar values.
  1990      * @since   1.5
  1991      */
  1992     public int compareTo(Calendar anotherCalendar) {
  1993         return compareTo(getMillisOf(anotherCalendar));
  1994     }
  1995 
  1996     /**
  1997      * Adds or subtracts the specified amount of time to the given calendar field,
  1998      * based on the calendar's rules. For example, to subtract 5 days from
  1999      * the current time of the calendar, you can achieve it by calling:
  2000      * <p><code>add(Calendar.DAY_OF_MONTH, -5)</code>.
  2001      *
  2002      * @param field the calendar field.
  2003      * @param amount the amount of date or time to be added to the field.
  2004      * @see #roll(int,int)
  2005      * @see #set(int,int)
  2006      */
  2007     abstract public void add(int field, int amount);
  2008 
  2009     /**
  2010      * Adds or subtracts (up/down) a single unit of time on the given time
  2011      * field without changing larger fields. For example, to roll the current
  2012      * date up by one day, you can achieve it by calling:
  2013      * <p>roll(Calendar.DATE, true).
  2014      * When rolling on the year or Calendar.YEAR field, it will roll the year
  2015      * value in the range between 1 and the value returned by calling
  2016      * <code>getMaximum(Calendar.YEAR)</code>.
  2017      * When rolling on the month or Calendar.MONTH field, other fields like
  2018      * date might conflict and, need to be changed. For instance,
  2019      * rolling the month on the date 01/31/96 will result in 02/29/96.
  2020      * When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will
  2021      * roll the hour value in the range between 0 and 23, which is zero-based.
  2022      *
  2023      * @param field the time field.
  2024      * @param up indicates if the value of the specified time field is to be
  2025      * rolled up or rolled down. Use true if rolling up, false otherwise.
  2026      * @see Calendar#add(int,int)
  2027      * @see Calendar#set(int,int)
  2028      */
  2029     abstract public void roll(int field, boolean up);
  2030 
  2031     /**
  2032      * Adds the specified (signed) amount to the specified calendar field
  2033      * without changing larger fields.  A negative amount means to roll
  2034      * down.
  2035      *
  2036      * <p>NOTE:  This default implementation on <code>Calendar</code> just repeatedly calls the
  2037      * version of {@link #roll(int,boolean) roll()} that rolls by one unit.  This may not
  2038      * always do the right thing.  For example, if the <code>DAY_OF_MONTH</code> field is 31,
  2039      * rolling through February will leave it set to 28.  The <code>GregorianCalendar</code>
  2040      * version of this function takes care of this problem.  Other subclasses
  2041      * should also provide overrides of this function that do the right thing.
  2042      *
  2043      * @param field the calendar field.
  2044      * @param amount the signed amount to add to the calendar <code>field</code>.
  2045      * @since 1.2
  2046      * @see #roll(int,boolean)
  2047      * @see #add(int,int)
  2048      * @see #set(int,int)
  2049      */
  2050     public void roll(int field, int amount)
  2051     {
  2052         while (amount > 0) {
  2053             roll(field, true);
  2054             amount--;
  2055         }
  2056         while (amount < 0) {
  2057             roll(field, false);
  2058             amount++;
  2059         }
  2060     }
  2061 
  2062     /**
  2063      * Sets the time zone with the given time zone value.
  2064      *
  2065      * @param value the given time zone.
  2066      */
  2067     public void setTimeZone(TimeZone value)
  2068     {
  2069         zone = value;
  2070         sharedZone = false;
  2071         /* Recompute the fields from the time using the new zone.  This also
  2072          * works if isTimeSet is false (after a call to set()).  In that case
  2073          * the time will be computed from the fields using the new zone, then
  2074          * the fields will get recomputed from that.  Consider the sequence of
  2075          * calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST).
  2076          * Is cal set to 1 o'clock EST or 1 o'clock PST?  Answer: PST.  More
  2077          * generally, a call to setTimeZone() affects calls to set() BEFORE AND
  2078          * AFTER it up to the next call to complete().
  2079          */
  2080         areAllFieldsSet = areFieldsSet = false;
  2081     }
  2082 
  2083     /**
  2084      * Gets the time zone.
  2085      *
  2086      * @return the time zone object associated with this calendar.
  2087      */
  2088     public TimeZone getTimeZone()
  2089     {
  2090         // If the TimeZone object is shared by other Calendar instances, then
  2091         // create a clone.
  2092         if (sharedZone) {
  2093             zone = (TimeZone) zone.clone();
  2094             sharedZone = false;
  2095         }
  2096         return zone;
  2097     }
  2098 
  2099     /**
  2100      * Returns the time zone (without cloning).
  2101      */
  2102     TimeZone getZone() {
  2103         return zone;
  2104     }
  2105 
  2106     /**
  2107      * Sets the sharedZone flag to <code>shared</code>.
  2108      */
  2109     void setZoneShared(boolean shared) {
  2110         sharedZone = shared;
  2111     }
  2112 
  2113     /**
  2114      * Specifies whether or not date/time interpretation is to be lenient.  With
  2115      * lenient interpretation, a date such as "February 942, 1996" will be
  2116      * treated as being equivalent to the 941st day after February 1, 1996.
  2117      * With strict (non-lenient) interpretation, such dates will cause an exception to be
  2118      * thrown. The default is lenient.
  2119      *
  2120      * @param lenient <code>true</code> if the lenient mode is to be turned
  2121      * on; <code>false</code> if it is to be turned off.
  2122      * @see #isLenient()
  2123      * @see java.text.DateFormat#setLenient
  2124      */
  2125     public void setLenient(boolean lenient)
  2126     {
  2127         this.lenient = lenient;
  2128     }
  2129 
  2130     /**
  2131      * Tells whether date/time interpretation is to be lenient.
  2132      *
  2133      * @return <code>true</code> if the interpretation mode of this calendar is lenient;
  2134      * <code>false</code> otherwise.
  2135      * @see #setLenient(boolean)
  2136      */
  2137     public boolean isLenient()
  2138     {
  2139         return lenient;
  2140     }
  2141 
  2142     /**
  2143      * Sets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
  2144      * <code>MONDAY</code> in France.
  2145      *
  2146      * @param value the given first day of the week.
  2147      * @see #getFirstDayOfWeek()
  2148      * @see #getMinimalDaysInFirstWeek()
  2149      */
  2150     public void setFirstDayOfWeek(int value)
  2151     {
  2152         if (firstDayOfWeek == value) {
  2153             return;
  2154         }
  2155         firstDayOfWeek = value;
  2156         invalidateWeekFields();
  2157     }
  2158 
  2159     /**
  2160      * Gets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
  2161      * <code>MONDAY</code> in France.
  2162      *
  2163      * @return the first day of the week.
  2164      * @see #setFirstDayOfWeek(int)
  2165      * @see #getMinimalDaysInFirstWeek()
  2166      */
  2167     public int getFirstDayOfWeek()
  2168     {
  2169         return firstDayOfWeek;
  2170     }
  2171 
  2172     /**
  2173      * Sets what the minimal days required in the first week of the year are;
  2174      * For example, if the first week is defined as one that contains the first
  2175      * day of the first month of a year, call this method with value 1. If it
  2176      * must be a full week, use value 7.
  2177      *
  2178      * @param value the given minimal days required in the first week
  2179      * of the year.
  2180      * @see #getMinimalDaysInFirstWeek()
  2181      */
  2182     public void setMinimalDaysInFirstWeek(int value)
  2183     {
  2184         if (minimalDaysInFirstWeek == value) {
  2185             return;
  2186         }
  2187         minimalDaysInFirstWeek = value;
  2188         invalidateWeekFields();
  2189     }
  2190 
  2191     /**
  2192      * Gets what the minimal days required in the first week of the year are;
  2193      * e.g., if the first week is defined as one that contains the first day
  2194      * of the first month of a year, this method returns 1. If
  2195      * the minimal days required must be a full week, this method
  2196      * returns 7.
  2197      *
  2198      * @return the minimal days required in the first week of the year.
  2199      * @see #setMinimalDaysInFirstWeek(int)
  2200      */
  2201     public int getMinimalDaysInFirstWeek()
  2202     {
  2203         return minimalDaysInFirstWeek;
  2204     }
  2205 
  2206     /**
  2207      * Returns whether this {@code Calendar} supports week dates.
  2208      *
  2209      * <p>The default implementation of this method returns {@code false}.
  2210      *
  2211      * @return {@code true} if this {@code Calendar} supports week dates;
  2212      *         {@code false} otherwise.
  2213      * @see #getWeekYear()
  2214      * @see #setWeekDate(int,int,int)
  2215      * @see #getWeeksInWeekYear()
  2216      * @since 1.7
  2217      */
  2218     public boolean isWeekDateSupported() {
  2219         return false;
  2220     }
  2221 
  2222     /**
  2223      * Returns the week year represented by this {@code Calendar}. The
  2224      * week year is in sync with the week cycle. The {@linkplain
  2225      * #getFirstDayOfWeek() first day of the first week} is the first
  2226      * day of the week year.
  2227      *
  2228      * <p>The default implementation of this method throws an
  2229      * {@link UnsupportedOperationException}.
  2230      *
  2231      * @return the week year of this {@code Calendar}
  2232      * @exception UnsupportedOperationException
  2233      *            if any week year numbering isn't supported
  2234      *            in this {@code Calendar}.
  2235      * @see #isWeekDateSupported()
  2236      * @see #getFirstDayOfWeek()
  2237      * @see #getMinimalDaysInFirstWeek()
  2238      * @since 1.7
  2239      */
  2240     public int getWeekYear() {
  2241         throw new UnsupportedOperationException();
  2242     }
  2243 
  2244     /**
  2245      * Sets the date of this {@code Calendar} with the the given date
  2246      * specifiers - week year, week of year, and day of week.
  2247      *
  2248      * <p>Unlike the {@code set} method, all of the calendar fields
  2249      * and {@code time} values are calculated upon return.
  2250      *
  2251      * <p>If {@code weekOfYear} is out of the valid week-of-year range
  2252      * in {@code weekYear}, the {@code weekYear} and {@code
  2253      * weekOfYear} values are adjusted in lenient mode, or an {@code
  2254      * IllegalArgumentException} is thrown in non-lenient mode.
  2255      *
  2256      * <p>The default implementation of this method throws an
  2257      * {@code UnsupportedOperationException}.
  2258      *
  2259      * @param weekYear   the week year
  2260      * @param weekOfYear the week number based on {@code weekYear}
  2261      * @param dayOfWeek  the day of week value: one of the constants
  2262      *                   for the {@link #DAY_OF_WEEK} field: {@link
  2263      *                   #SUNDAY}, ..., {@link #SATURDAY}.
  2264      * @exception IllegalArgumentException
  2265      *            if any of the given date specifiers is invalid
  2266      *            or any of the calendar fields are inconsistent
  2267      *            with the given date specifiers in non-lenient mode
  2268      * @exception UnsupportedOperationException
  2269      *            if any week year numbering isn't supported in this
  2270      *            {@code Calendar}.
  2271      * @see #isWeekDateSupported()
  2272      * @see #getFirstDayOfWeek()
  2273      * @see #getMinimalDaysInFirstWeek()
  2274      * @since 1.7
  2275      */
  2276     public void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) {
  2277         throw new UnsupportedOperationException();
  2278     }
  2279 
  2280     /**
  2281      * Returns the number of weeks in the week year represented by this
  2282      * {@code Calendar}.
  2283      *
  2284      * <p>The default implementation of this method throws an
  2285      * {@code UnsupportedOperationException}.
  2286      *
  2287      * @return the number of weeks in the week year.
  2288      * @exception UnsupportedOperationException
  2289      *            if any week year numbering isn't supported in this
  2290      *            {@code Calendar}.
  2291      * @see #WEEK_OF_YEAR
  2292      * @see #isWeekDateSupported()
  2293      * @see #getWeekYear()
  2294      * @see #getActualMaximum(int)
  2295      * @since 1.7
  2296      */
  2297     public int getWeeksInWeekYear() {
  2298         throw new UnsupportedOperationException();
  2299     }
  2300 
  2301     /**
  2302      * Returns the minimum value for the given calendar field of this
  2303      * <code>Calendar</code> instance. The minimum value is defined as
  2304      * the smallest value returned by the {@link #get(int) get} method
  2305      * for any possible time value.  The minimum value depends on
  2306      * calendar system specific parameters of the instance.
  2307      *
  2308      * @param field the calendar field.
  2309      * @return the minimum value for the given calendar field.
  2310      * @see #getMaximum(int)
  2311      * @see #getGreatestMinimum(int)
  2312      * @see #getLeastMaximum(int)
  2313      * @see #getActualMinimum(int)
  2314      * @see #getActualMaximum(int)
  2315      */
  2316     abstract public int getMinimum(int field);
  2317 
  2318     /**
  2319      * Returns the maximum value for the given calendar field of this
  2320      * <code>Calendar</code> instance. The maximum value is defined as
  2321      * the largest value returned by the {@link #get(int) get} method
  2322      * for any possible time value. The maximum value depends on
  2323      * calendar system specific parameters of the instance.
  2324      *
  2325      * @param field the calendar field.
  2326      * @return the maximum value for the given calendar field.
  2327      * @see #getMinimum(int)
  2328      * @see #getGreatestMinimum(int)
  2329      * @see #getLeastMaximum(int)
  2330      * @see #getActualMinimum(int)
  2331      * @see #getActualMaximum(int)
  2332      */
  2333     abstract public int getMaximum(int field);
  2334 
  2335     /**
  2336      * Returns the highest minimum value for the given calendar field
  2337      * of this <code>Calendar</code> instance. The highest minimum
  2338      * value is defined as the largest value returned by {@link
  2339      * #getActualMinimum(int)} for any possible time value. The
  2340      * greatest minimum value depends on calendar system specific
  2341      * parameters of the instance.
  2342      *
  2343      * @param field the calendar field.
  2344      * @return the highest minimum value for the given calendar field.
  2345      * @see #getMinimum(int)
  2346      * @see #getMaximum(int)
  2347      * @see #getLeastMaximum(int)
  2348      * @see #getActualMinimum(int)
  2349      * @see #getActualMaximum(int)
  2350      */
  2351     abstract public int getGreatestMinimum(int field);
  2352 
  2353     /**
  2354      * Returns the lowest maximum value for the given calendar field
  2355      * of this <code>Calendar</code> instance. The lowest maximum
  2356      * value is defined as the smallest value returned by {@link
  2357      * #getActualMaximum(int)} for any possible time value. The least
  2358      * maximum value depends on calendar system specific parameters of
  2359      * the instance. For example, a <code>Calendar</code> for the
  2360      * Gregorian calendar system returns 28 for the
  2361      * <code>DAY_OF_MONTH</code> field, because the 28th is the last
  2362      * day of the shortest month of this calendar, February in a
  2363      * common year.
  2364      *
  2365      * @param field the calendar field.
  2366      * @return the lowest maximum value for the given calendar field.
  2367      * @see #getMinimum(int)
  2368      * @see #getMaximum(int)
  2369      * @see #getGreatestMinimum(int)
  2370      * @see #getActualMinimum(int)
  2371      * @see #getActualMaximum(int)
  2372      */
  2373     abstract public int getLeastMaximum(int field);
  2374 
  2375     /**
  2376      * Returns the minimum value that the specified calendar field
  2377      * could have, given the time value of this <code>Calendar</code>.
  2378      *
  2379      * <p>The default implementation of this method uses an iterative
  2380      * algorithm to determine the actual minimum value for the
  2381      * calendar field. Subclasses should, if possible, override this
  2382      * with a more efficient implementation - in many cases, they can
  2383      * simply return <code>getMinimum()</code>.
  2384      *
  2385      * @param field the calendar field
  2386      * @return the minimum of the given calendar field for the time
  2387      * value of this <code>Calendar</code>
  2388      * @see #getMinimum(int)
  2389      * @see #getMaximum(int)
  2390      * @see #getGreatestMinimum(int)
  2391      * @see #getLeastMaximum(int)
  2392      * @see #getActualMaximum(int)
  2393      * @since 1.2
  2394      */
  2395     public int getActualMinimum(int field) {
  2396         int fieldValue = getGreatestMinimum(field);
  2397         int endValue = getMinimum(field);
  2398 
  2399         // if we know that the minimum value is always the same, just return it
  2400         if (fieldValue == endValue) {
  2401             return fieldValue;
  2402         }
  2403 
  2404         // clone the calendar so we don't mess with the real one, and set it to
  2405         // accept anything for the field values
  2406         Calendar work = (Calendar)this.clone();
  2407         work.setLenient(true);
  2408 
  2409         // now try each value from getLeastMaximum() to getMaximum() one by one until
  2410         // we get a value that normalizes to another value.  The last value that
  2411         // normalizes to itself is the actual minimum for the current date
  2412         int result = fieldValue;
  2413 
  2414         do {
  2415             work.set(field, fieldValue);
  2416             if (work.get(field) != fieldValue) {
  2417                 break;
  2418             } else {
  2419                 result = fieldValue;
  2420                 fieldValue--;
  2421             }
  2422         } while (fieldValue >= endValue);
  2423 
  2424         return result;
  2425     }
  2426 
  2427     /**
  2428      * Returns the maximum value that the specified calendar field
  2429      * could have, given the time value of this
  2430      * <code>Calendar</code>. For example, the actual maximum value of
  2431      * the <code>MONTH</code> field is 12 in some years, and 13 in
  2432      * other years in the Hebrew calendar system.
  2433      *
  2434      * <p>The default implementation of this method uses an iterative
  2435      * algorithm to determine the actual maximum value for the
  2436      * calendar field. Subclasses should, if possible, override this
  2437      * with a more efficient implementation.
  2438      *
  2439      * @param field the calendar field
  2440      * @return the maximum of the given calendar field for the time
  2441      * value of this <code>Calendar</code>
  2442      * @see #getMinimum(int)
  2443      * @see #getMaximum(int)
  2444      * @see #getGreatestMinimum(int)
  2445      * @see #getLeastMaximum(int)
  2446      * @see #getActualMinimum(int)
  2447      * @since 1.2
  2448      */
  2449     public int getActualMaximum(int field) {
  2450         int fieldValue = getLeastMaximum(field);
  2451         int endValue = getMaximum(field);
  2452 
  2453         // if we know that the maximum value is always the same, just return it.
  2454         if (fieldValue == endValue) {
  2455             return fieldValue;
  2456         }
  2457 
  2458         // clone the calendar so we don't mess with the real one, and set it to
  2459         // accept anything for the field values.
  2460         Calendar work = (Calendar)this.clone();
  2461         work.setLenient(true);
  2462 
  2463         // if we're counting weeks, set the day of the week to Sunday.  We know the
  2464         // last week of a month or year will contain the first day of the week.
  2465         if (field == WEEK_OF_YEAR || field == WEEK_OF_MONTH)
  2466             work.set(DAY_OF_WEEK, firstDayOfWeek);
  2467 
  2468         // now try each value from getLeastMaximum() to getMaximum() one by one until
  2469         // we get a value that normalizes to another value.  The last value that
  2470         // normalizes to itself is the actual maximum for the current date
  2471         int result = fieldValue;
  2472 
  2473         do {
  2474             work.set(field, fieldValue);
  2475             if (work.get(field) != fieldValue) {
  2476                 break;
  2477             } else {
  2478                 result = fieldValue;
  2479                 fieldValue++;
  2480             }
  2481         } while (fieldValue <= endValue);
  2482 
  2483         return result;
  2484     }
  2485 
  2486     /**
  2487      * Creates and returns a copy of this object.
  2488      *
  2489      * @return a copy of this object.
  2490      */
  2491     public Object clone()
  2492     {
  2493         try {
  2494             Calendar other = (Calendar) super.clone();
  2495 
  2496             other.fields = new int[FIELD_COUNT];
  2497             other.isSet = new boolean[FIELD_COUNT];
  2498             other.stamp = new int[FIELD_COUNT];
  2499             for (int i = 0; i < FIELD_COUNT; i++) {
  2500                 other.fields[i] = fields[i];
  2501                 other.stamp[i] = stamp[i];
  2502                 other.isSet[i] = isSet[i];
  2503             }
  2504             other.zone = (TimeZone) zone.clone();
  2505             return other;
  2506         }
  2507         catch (CloneNotSupportedException e) {
  2508             // this shouldn't happen, since we are Cloneable
  2509             throw new InternalError();
  2510         }
  2511     }
  2512 
  2513     private static final String[] FIELD_NAME = {
  2514         "ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH",
  2515         "DAY_OF_YEAR", "DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR",
  2516         "HOUR_OF_DAY", "MINUTE", "SECOND", "MILLISECOND", "ZONE_OFFSET",
  2517         "DST_OFFSET"
  2518     };
  2519 
  2520     /**
  2521      * Returns the name of the specified calendar field.
  2522      *
  2523      * @param field the calendar field
  2524      * @return the calendar field name
  2525      * @exception IndexOutOfBoundsException if <code>field</code> is negative,
  2526      * equal to or greater then <code>FIELD_COUNT</code>.
  2527      */
  2528     static final String getFieldName(int field) {
  2529         return FIELD_NAME[field];
  2530     }
  2531 
  2532     /**
  2533      * Return a string representation of this calendar. This method
  2534      * is intended to be used only for debugging purposes, and the
  2535      * format of the returned string may vary between implementations.
  2536      * The returned string may be empty but may not be <code>null</code>.
  2537      *
  2538      * @return  a string representation of this calendar.
  2539      */
  2540     public String toString() {
  2541         // NOTE: BuddhistCalendar.toString() interprets the string
  2542         // produced by this method so that the Gregorian year number
  2543         // is substituted by its B.E. year value. It relies on
  2544         // "...,YEAR=<year>,..." or "...,YEAR=?,...".
  2545         StringBuilder buffer = new StringBuilder(800);
  2546         buffer.append(getClass().getName()).append('[');
  2547         appendValue(buffer, "time", isTimeSet, time);
  2548         buffer.append(",areFieldsSet=").append(areFieldsSet);
  2549         buffer.append(",areAllFieldsSet=").append(areAllFieldsSet);
  2550         buffer.append(",lenient=").append(lenient);
  2551         buffer.append(",zone=").append(zone);
  2552         appendValue(buffer, ",firstDayOfWeek", true, (long) firstDayOfWeek);
  2553         appendValue(buffer, ",minimalDaysInFirstWeek", true, (long) minimalDaysInFirstWeek);
  2554         for (int i = 0; i < FIELD_COUNT; ++i) {
  2555             buffer.append(',');
  2556             appendValue(buffer, FIELD_NAME[i], isSet(i), (long) fields[i]);
  2557         }
  2558         buffer.append(']');
  2559         return buffer.toString();
  2560     }
  2561 
  2562     // =======================privates===============================
  2563 
  2564     private static final void appendValue(StringBuilder sb, String item, boolean valid, long value) {
  2565         sb.append(item).append('=');
  2566         if (valid) {
  2567             sb.append(value);
  2568         } else {
  2569             sb.append('?');
  2570         }
  2571     }
  2572 
  2573     /**
  2574      * Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent.
  2575      * They are used to figure out the week count for a specific date for
  2576      * a given locale. These must be set when a Calendar is constructed.
  2577      * @param desiredLocale the given locale.
  2578      */
  2579     private void setWeekCountData(Locale desiredLocale)
  2580     {
  2581         /* try to get the Locale data from the cache */
  2582         int[] data = cachedLocaleData.get(desiredLocale);
  2583         if (data == null) {  /* cache miss */
  2584 //            ResourceBundle bundle = LocaleData.getCalendarData(desiredLocale);
  2585             data = new int[2];
  2586 //            data[0] = Integer.parseInt(bundle.getString("firstDayOfWeek"));
  2587 //            data[1] = Integer.parseInt(bundle.getString("minimalDaysInFirstWeek"));
  2588             cachedLocaleData.putIfAbsent(desiredLocale, data);
  2589         }
  2590         firstDayOfWeek = data[0];
  2591         minimalDaysInFirstWeek = data[1];
  2592     }
  2593 
  2594     /**
  2595      * Recomputes the time and updates the status fields isTimeSet
  2596      * and areFieldsSet.  Callers should check isTimeSet and only
  2597      * call this method if isTimeSet is false.
  2598      */
  2599     private void updateTime() {
  2600         computeTime();
  2601         // The areFieldsSet and areAllFieldsSet values are no longer
  2602         // controlled here (as of 1.5).
  2603         isTimeSet = true;
  2604     }
  2605 
  2606     private int compareTo(long t) {
  2607         long thisTime = getMillisOf(this);
  2608         return (thisTime > t) ? 1 : (thisTime == t) ? 0 : -1;
  2609     }
  2610 
  2611     private static final long getMillisOf(Calendar calendar) {
  2612         if (calendar.isTimeSet) {
  2613             return calendar.time;
  2614         }
  2615         Calendar cal = (Calendar) calendar.clone();
  2616         cal.setLenient(true);
  2617         return cal.getTimeInMillis();
  2618     }
  2619 
  2620     /**
  2621      * Adjusts the stamp[] values before nextStamp overflow. nextStamp
  2622      * is set to the next stamp value upon the return.
  2623      */
  2624     private final void adjustStamp() {
  2625         int max = MINIMUM_USER_STAMP;
  2626         int newStamp = MINIMUM_USER_STAMP;
  2627 
  2628         for (;;) {
  2629             int min = Integer.MAX_VALUE;
  2630             for (int i = 0; i < stamp.length; i++) {
  2631                 int v = stamp[i];
  2632                 if (v >= newStamp && min > v) {
  2633                     min = v;
  2634                 }
  2635                 if (max < v) {
  2636                     max = v;
  2637                 }
  2638             }
  2639             if (max != min && min == Integer.MAX_VALUE) {
  2640                 break;
  2641             }
  2642             for (int i = 0; i < stamp.length; i++) {
  2643                 if (stamp[i] == min) {
  2644                     stamp[i] = newStamp;
  2645                 }
  2646             }
  2647             newStamp++;
  2648             if (min == max) {
  2649                 break;
  2650             }
  2651         }
  2652         nextStamp = newStamp;
  2653     }
  2654 
  2655     /**
  2656      * Sets the WEEK_OF_MONTH and WEEK_OF_YEAR fields to new values with the
  2657      * new parameter value if they have been calculated internally.
  2658      */
  2659     private void invalidateWeekFields()
  2660     {
  2661         if (stamp[WEEK_OF_MONTH] != COMPUTED &&
  2662             stamp[WEEK_OF_YEAR] != COMPUTED) {
  2663             return;
  2664         }
  2665 
  2666         // We have to check the new values of these fields after changing
  2667         // firstDayOfWeek and/or minimalDaysInFirstWeek. If the field values
  2668         // have been changed, then set the new values. (4822110)
  2669         Calendar cal = (Calendar) clone();
  2670         cal.setLenient(true);
  2671         cal.clear(WEEK_OF_MONTH);
  2672         cal.clear(WEEK_OF_YEAR);
  2673 
  2674         if (stamp[WEEK_OF_MONTH] == COMPUTED) {
  2675             int weekOfMonth = cal.get(WEEK_OF_MONTH);
  2676             if (fields[WEEK_OF_MONTH] != weekOfMonth) {
  2677                 fields[WEEK_OF_MONTH] = weekOfMonth;
  2678             }
  2679         }
  2680 
  2681         if (stamp[WEEK_OF_YEAR] == COMPUTED) {
  2682             int weekOfYear = cal.get(WEEK_OF_YEAR);
  2683             if (fields[WEEK_OF_YEAR] != weekOfYear) {
  2684                 fields[WEEK_OF_YEAR] = weekOfYear;
  2685             }
  2686         }
  2687     }
  2688 
  2689     /**
  2690      * Save the state of this object to a stream (i.e., serialize it).
  2691      *
  2692      * Ideally, <code>Calendar</code> would only write out its state data and
  2693      * the current time, and not write any field data out, such as
  2694      * <code>fields[]</code>, <code>isTimeSet</code>, <code>areFieldsSet</code>,
  2695      * and <code>isSet[]</code>.  <code>nextStamp</code> also should not be part
  2696      * of the persistent state. Unfortunately, this didn't happen before JDK 1.1
  2697      * shipped. To be compatible with JDK 1.1, we will always have to write out
  2698      * the field values and state flags.  However, <code>nextStamp</code> can be
  2699      * removed from the serialization stream; this will probably happen in the
  2700      * near future.
  2701      */
  2702     private void writeObject(ObjectOutputStream stream)
  2703          throws IOException
  2704     {
  2705         // Try to compute the time correctly, for the future (stream
  2706         // version 2) in which we don't write out fields[] or isSet[].
  2707         if (!isTimeSet) {
  2708             try {
  2709                 updateTime();
  2710             }
  2711             catch (IllegalArgumentException e) {}
  2712         }
  2713 
  2714         // If this Calendar has a ZoneInfo, save it and set a
  2715         // SimpleTimeZone equivalent (as a single DST schedule) for
  2716         // backward compatibility.
  2717         TimeZone savedZone = null;
  2718 //        if (zone instanceof ZoneInfo) {
  2719 //            SimpleTimeZone stz = ((ZoneInfo)zone).getLastRuleInstance();
  2720 //            if (stz == null) {
  2721 //                stz = new SimpleTimeZone(zone.getRawOffset(), zone.getID());
  2722 //            }
  2723 //            savedZone = zone;
  2724 //            zone = stz;
  2725 //        }
  2726 
  2727         // Write out the 1.1 FCS object.
  2728         stream.defaultWriteObject();
  2729 
  2730         // Write out the ZoneInfo object
  2731         // 4802409: we write out even if it is null, a temporary workaround
  2732         // the real fix for bug 4844924 in corba-iiop
  2733         stream.writeObject(savedZone);
  2734         if (savedZone != null) {
  2735             zone = savedZone;
  2736         }
  2737     }
  2738 
  2739     /**
  2740      * Reconstitutes this object from a stream (i.e., deserialize it).
  2741      */
  2742     private void readObject(ObjectInputStream stream)
  2743          throws IOException, ClassNotFoundException
  2744     {
  2745         final ObjectInputStream input = stream;
  2746         input.defaultReadObject();
  2747 
  2748         stamp = new int[FIELD_COUNT];
  2749 
  2750         // Starting with version 2 (not implemented yet), we expect that
  2751         // fields[], isSet[], isTimeSet, and areFieldsSet may not be
  2752         // streamed out anymore.  We expect 'time' to be correct.
  2753         if (serialVersionOnStream >= 2)
  2754         {
  2755             isTimeSet = true;
  2756             if (fields == null) fields = new int[FIELD_COUNT];
  2757             if (isSet == null) isSet = new boolean[FIELD_COUNT];
  2758         }
  2759         else if (serialVersionOnStream >= 0)
  2760         {
  2761             for (int i=0; i<FIELD_COUNT; ++i)
  2762                 stamp[i] = isSet[i] ? COMPUTED : UNSET;
  2763         }
  2764 
  2765         serialVersionOnStream = currentSerialVersion;
  2766 
  2767         // If there's a ZoneInfo object, use it for zone.
  2768         TimeZone zi = null;
  2769 //        try {
  2770 //            zi = AccessController.doPrivileged(
  2771 //                    new PrivilegedExceptionAction<ZoneInfo>() {
  2772 //                        public ZoneInfo run() throws Exception {
  2773 //                            return (ZoneInfo) input.readObject();
  2774 //                        }
  2775 //                    },
  2776 //                    CalendarAccessControlContext.INSTANCE);
  2777 //        } catch (PrivilegedActionException pae) {
  2778 //            Exception e = pae.getException();
  2779 //            if (!(e instanceof OptionalDataException)) {
  2780 //                if (e instanceof RuntimeException) {
  2781 //                    throw (RuntimeException) e;
  2782 //                } else if (e instanceof IOException) {
  2783 //                    throw (IOException) e;
  2784 //                } else if (e instanceof ClassNotFoundException) {
  2785 //                    throw (ClassNotFoundException) e;
  2786 //                }
  2787 //                throw new RuntimeException(e);
  2788 //            }
  2789 //        }
  2790         if (zi != null) {
  2791             zone = zi;
  2792         }
  2793 
  2794         // If the deserialized object has a SimpleTimeZone, try to
  2795         // replace it with a ZoneInfo equivalent (as of 1.4) in order
  2796         // to be compatible with the SimpleTimeZone-based
  2797         // implementation as much as possible.
  2798         if (zone instanceof SimpleTimeZone) {
  2799             String id = zone.getID();
  2800             TimeZone tz = TimeZone.getTimeZone(id);
  2801             if (tz != null && tz.hasSameRules(zone) && tz.getID().equals(id)) {
  2802                 zone = tz;
  2803             }
  2804         }
  2805     }
  2806 }