jdk/src/java.base/share/classes/java/util/Calendar.java
changeset 25859 3317bb8137f4
parent 24865 09b1d992ca72
child 28059 e576535359cc
equal deleted inserted replaced
25858:836adbf7a2cd 25859:3317bb8137f4
       
     1 /*
       
     2  * Copyright (c) 1996, 2013, 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.AccessControlContext;
       
    47 import java.security.AccessController;
       
    48 import java.security.PermissionCollection;
       
    49 import java.security.PrivilegedActionException;
       
    50 import java.security.PrivilegedExceptionAction;
       
    51 import java.security.ProtectionDomain;
       
    52 import java.text.DateFormat;
       
    53 import java.text.DateFormatSymbols;
       
    54 import java.time.Instant;
       
    55 import java.util.concurrent.ConcurrentHashMap;
       
    56 import java.util.concurrent.ConcurrentMap;
       
    57 import sun.util.BuddhistCalendar;
       
    58 import sun.util.calendar.ZoneInfo;
       
    59 import sun.util.locale.provider.CalendarDataUtility;
       
    60 import sun.util.locale.provider.LocaleProviderAdapter;
       
    61 import sun.util.spi.CalendarProvider;
       
    62 
       
    63 /**
       
    64  * The <code>Calendar</code> class is an abstract class that provides methods
       
    65  * for converting between a specific instant in time and a set of {@link
       
    66  * #fields calendar fields} such as <code>YEAR</code>, <code>MONTH</code>,
       
    67  * <code>DAY_OF_MONTH</code>, <code>HOUR</code>, and so on, and for
       
    68  * manipulating the calendar fields, such as getting the date of the next
       
    69  * week. An instant in time can be represented by a millisecond value that is
       
    70  * an offset from the <a name="Epoch"><em>Epoch</em></a>, January 1, 1970
       
    71  * 00:00:00.000 GMT (Gregorian).
       
    72  *
       
    73  * <p>The class also provides additional fields and methods for
       
    74  * implementing a concrete calendar system outside the package. Those
       
    75  * fields and methods are defined as <code>protected</code>.
       
    76  *
       
    77  * <p>
       
    78  * Like other locale-sensitive classes, <code>Calendar</code> provides a
       
    79  * class method, <code>getInstance</code>, for getting a generally useful
       
    80  * object of this type. <code>Calendar</code>'s <code>getInstance</code> method
       
    81  * returns a <code>Calendar</code> object whose
       
    82  * calendar fields have been initialized with the current date and time:
       
    83  * <blockquote>
       
    84  * <pre>
       
    85  *     Calendar rightNow = Calendar.getInstance();
       
    86  * </pre>
       
    87  * </blockquote>
       
    88  *
       
    89  * <p>A <code>Calendar</code> object can produce all the calendar field values
       
    90  * needed to implement the date-time formatting for a particular language and
       
    91  * calendar style (for example, Japanese-Gregorian, Japanese-Traditional).
       
    92  * <code>Calendar</code> defines the range of values returned by
       
    93  * certain calendar fields, as well as their meaning.  For example,
       
    94  * the first month of the calendar system has value <code>MONTH ==
       
    95  * JANUARY</code> for all calendars.  Other values are defined by the
       
    96  * concrete subclass, such as <code>ERA</code>.  See individual field
       
    97  * documentation and subclass documentation for details.
       
    98  *
       
    99  * <h3>Getting and Setting Calendar Field Values</h3>
       
   100  *
       
   101  * <p>The calendar field values can be set by calling the <code>set</code>
       
   102  * methods. Any field values set in a <code>Calendar</code> will not be
       
   103  * interpreted until it needs to calculate its time value (milliseconds from
       
   104  * the Epoch) or values of the calendar fields. Calling the
       
   105  * <code>get</code>, <code>getTimeInMillis</code>, <code>getTime</code>,
       
   106  * <code>add</code> and <code>roll</code> involves such calculation.
       
   107  *
       
   108  * <h4>Leniency</h4>
       
   109  *
       
   110  * <p><code>Calendar</code> has two modes for interpreting the calendar
       
   111  * fields, <em>lenient</em> and <em>non-lenient</em>.  When a
       
   112  * <code>Calendar</code> is in lenient mode, it accepts a wider range of
       
   113  * calendar field values than it produces.  When a <code>Calendar</code>
       
   114  * recomputes calendar field values for return by <code>get()</code>, all of
       
   115  * the calendar fields are normalized. For example, a lenient
       
   116  * <code>GregorianCalendar</code> interprets <code>MONTH == JANUARY</code>,
       
   117  * <code>DAY_OF_MONTH == 32</code> as February 1.
       
   118 
       
   119  * <p>When a <code>Calendar</code> is in non-lenient mode, it throws an
       
   120  * exception if there is any inconsistency in its calendar fields. For
       
   121  * example, a <code>GregorianCalendar</code> always produces
       
   122  * <code>DAY_OF_MONTH</code> values between 1 and the length of the month. A
       
   123  * non-lenient <code>GregorianCalendar</code> throws an exception upon
       
   124  * calculating its time or calendar field values if any out-of-range field
       
   125  * value has been set.
       
   126  *
       
   127  * <h4><a name="first_week">First Week</a></h4>
       
   128  *
       
   129  * <code>Calendar</code> defines a locale-specific seven day week using two
       
   130  * parameters: the first day of the week and the minimal days in first week
       
   131  * (from 1 to 7).  These numbers are taken from the locale resource data when a
       
   132  * <code>Calendar</code> is constructed.  They may also be specified explicitly
       
   133  * through the methods for setting their values.
       
   134  *
       
   135  * <p>When setting or getting the <code>WEEK_OF_MONTH</code> or
       
   136  * <code>WEEK_OF_YEAR</code> fields, <code>Calendar</code> must determine the
       
   137  * first week of the month or year as a reference point.  The first week of a
       
   138  * month or year is defined as the earliest seven day period beginning on
       
   139  * <code>getFirstDayOfWeek()</code> and containing at least
       
   140  * <code>getMinimalDaysInFirstWeek()</code> days of that month or year.  Weeks
       
   141  * numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow
       
   142  * it.  Note that the normalized numbering returned by <code>get()</code> may be
       
   143  * different.  For example, a specific <code>Calendar</code> subclass may
       
   144  * designate the week before week 1 of a year as week <code><i>n</i></code> of
       
   145  * the previous year.
       
   146  *
       
   147  * <h4>Calendar Fields Resolution</h4>
       
   148  *
       
   149  * When computing a date and time from the calendar fields, there
       
   150  * may be insufficient information for the computation (such as only
       
   151  * year and month with no day of month), or there may be inconsistent
       
   152  * information (such as Tuesday, July 15, 1996 (Gregorian) -- July 15,
       
   153  * 1996 is actually a Monday). <code>Calendar</code> will resolve
       
   154  * calendar field values to determine the date and time in the
       
   155  * following way.
       
   156  *
       
   157  * <p><a name="resolution">If there is any conflict in calendar field values,
       
   158  * <code>Calendar</code> gives priorities to calendar fields that have been set
       
   159  * more recently.</a> The following are the default combinations of the
       
   160  * calendar fields. The most recent combination, as determined by the
       
   161  * most recently set single field, will be used.
       
   162  *
       
   163  * <p><a name="date_resolution">For the date fields</a>:
       
   164  * <blockquote>
       
   165  * <pre>
       
   166  * YEAR + MONTH + DAY_OF_MONTH
       
   167  * YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
       
   168  * YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
       
   169  * YEAR + DAY_OF_YEAR
       
   170  * YEAR + DAY_OF_WEEK + WEEK_OF_YEAR
       
   171  * </pre></blockquote>
       
   172  *
       
   173  * <a name="time_resolution">For the time of day fields</a>:
       
   174  * <blockquote>
       
   175  * <pre>
       
   176  * HOUR_OF_DAY
       
   177  * AM_PM + HOUR
       
   178  * </pre></blockquote>
       
   179  *
       
   180  * <p>If there are any calendar fields whose values haven't been set in the selected
       
   181  * field combination, <code>Calendar</code> uses their default values. The default
       
   182  * value of each field may vary by concrete calendar systems. For example, in
       
   183  * <code>GregorianCalendar</code>, the default of a field is the same as that
       
   184  * of the start of the Epoch: i.e., <code>YEAR = 1970</code>, <code>MONTH =
       
   185  * JANUARY</code>, <code>DAY_OF_MONTH = 1</code>, etc.
       
   186  *
       
   187  * <p>
       
   188  * <strong>Note:</strong> There are certain possible ambiguities in
       
   189  * interpretation of certain singular times, which are resolved in the
       
   190  * following ways:
       
   191  * <ol>
       
   192  *     <li> 23:59 is the last minute of the day and 00:00 is the first
       
   193  *          minute of the next day. Thus, 23:59 on Dec 31, 1999 &lt; 00:00 on
       
   194  *          Jan 1, 2000 &lt; 00:01 on Jan 1, 2000.
       
   195  *
       
   196  *     <li> Although historically not precise, midnight also belongs to "am",
       
   197  *          and noon belongs to "pm", so on the same day,
       
   198  *          12:00 am (midnight) &lt; 12:01 am, and 12:00 pm (noon) &lt; 12:01 pm
       
   199  * </ol>
       
   200  *
       
   201  * <p>
       
   202  * The date or time format strings are not part of the definition of a
       
   203  * calendar, as those must be modifiable or overridable by the user at
       
   204  * runtime. Use {@link DateFormat}
       
   205  * to format dates.
       
   206  *
       
   207  * <h4>Field Manipulation</h4>
       
   208  *
       
   209  * The calendar fields can be changed using three methods:
       
   210  * <code>set()</code>, <code>add()</code>, and <code>roll()</code>.
       
   211  *
       
   212  * <p><strong><code>set(f, value)</code></strong> changes calendar field
       
   213  * <code>f</code> to <code>value</code>.  In addition, it sets an
       
   214  * internal member variable to indicate that calendar field <code>f</code> has
       
   215  * been changed. Although calendar field <code>f</code> is changed immediately,
       
   216  * the calendar's time value in milliseconds is not recomputed until the next call to
       
   217  * <code>get()</code>, <code>getTime()</code>, <code>getTimeInMillis()</code>,
       
   218  * <code>add()</code>, or <code>roll()</code> is made. Thus, multiple calls to
       
   219  * <code>set()</code> do not trigger multiple, unnecessary
       
   220  * computations. As a result of changing a calendar field using
       
   221  * <code>set()</code>, other calendar fields may also change, depending on the
       
   222  * calendar field, the calendar field value, and the calendar system. In addition,
       
   223  * <code>get(f)</code> will not necessarily return <code>value</code> set by
       
   224  * the call to the <code>set</code> method
       
   225  * after the calendar fields have been recomputed. The specifics are determined by
       
   226  * the concrete calendar class.</p>
       
   227  *
       
   228  * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
       
   229  * originally set to August 31, 1999. Calling <code>set(Calendar.MONTH,
       
   230  * Calendar.SEPTEMBER)</code> sets the date to September 31,
       
   231  * 1999. This is a temporary internal representation that resolves to
       
   232  * October 1, 1999 if <code>getTime()</code>is then called. However, a
       
   233  * call to <code>set(Calendar.DAY_OF_MONTH, 30)</code> before the call to
       
   234  * <code>getTime()</code> sets the date to September 30, 1999, since
       
   235  * no recomputation occurs after <code>set()</code> itself.</p>
       
   236  *
       
   237  * <p><strong><code>add(f, delta)</code></strong> adds <code>delta</code>
       
   238  * to field <code>f</code>.  This is equivalent to calling <code>set(f,
       
   239  * get(f) + delta)</code> with two adjustments:</p>
       
   240  *
       
   241  * <blockquote>
       
   242  *   <p><strong>Add rule 1</strong>. The value of field <code>f</code>
       
   243  *   after the call minus the value of field <code>f</code> before the
       
   244  *   call is <code>delta</code>, modulo any overflow that has occurred in
       
   245  *   field <code>f</code>. Overflow occurs when a field value exceeds its
       
   246  *   range and, as a result, the next larger field is incremented or
       
   247  *   decremented and the field value is adjusted back into its range.</p>
       
   248  *
       
   249  *   <p><strong>Add rule 2</strong>. If a smaller field is expected to be
       
   250  *   invariant, but it is impossible for it to be equal to its
       
   251  *   prior value because of changes in its minimum or maximum after field
       
   252  *   <code>f</code> is changed or other constraints, such as time zone
       
   253  *   offset changes, then its value is adjusted to be as close
       
   254  *   as possible to its expected value. A smaller field represents a
       
   255  *   smaller unit of time. <code>HOUR</code> is a smaller field than
       
   256  *   <code>DAY_OF_MONTH</code>. No adjustment is made to smaller fields
       
   257  *   that are not expected to be invariant. The calendar system
       
   258  *   determines what fields are expected to be invariant.</p>
       
   259  * </blockquote>
       
   260  *
       
   261  * <p>In addition, unlike <code>set()</code>, <code>add()</code> forces
       
   262  * an immediate recomputation of the calendar's milliseconds and all
       
   263  * fields.</p>
       
   264  *
       
   265  * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
       
   266  * originally set to August 31, 1999. Calling <code>add(Calendar.MONTH,
       
   267  * 13)</code> sets the calendar to September 30, 2000. <strong>Add rule
       
   268  * 1</strong> sets the <code>MONTH</code> field to September, since
       
   269  * adding 13 months to August gives September of the next year. Since
       
   270  * <code>DAY_OF_MONTH</code> cannot be 31 in September in a
       
   271  * <code>GregorianCalendar</code>, <strong>add rule 2</strong> sets the
       
   272  * <code>DAY_OF_MONTH</code> to 30, the closest possible value. Although
       
   273  * it is a smaller field, <code>DAY_OF_WEEK</code> is not adjusted by
       
   274  * rule 2, since it is expected to change when the month changes in a
       
   275  * <code>GregorianCalendar</code>.</p>
       
   276  *
       
   277  * <p><strong><code>roll(f, delta)</code></strong> adds
       
   278  * <code>delta</code> to field <code>f</code> without changing larger
       
   279  * fields. This is equivalent to calling <code>add(f, delta)</code> with
       
   280  * the following adjustment:</p>
       
   281  *
       
   282  * <blockquote>
       
   283  *   <p><strong>Roll rule</strong>. Larger fields are unchanged after the
       
   284  *   call. A larger field represents a larger unit of
       
   285  *   time. <code>DAY_OF_MONTH</code> is a larger field than
       
   286  *   <code>HOUR</code>.</p>
       
   287  * </blockquote>
       
   288  *
       
   289  * <p><em>Example</em>: See {@link java.util.GregorianCalendar#roll(int, int)}.
       
   290  *
       
   291  * <p><strong>Usage model</strong>. To motivate the behavior of
       
   292  * <code>add()</code> and <code>roll()</code>, consider a user interface
       
   293  * component with increment and decrement buttons for the month, day, and
       
   294  * year, and an underlying <code>GregorianCalendar</code>. If the
       
   295  * interface reads January 31, 1999 and the user presses the month
       
   296  * increment button, what should it read? If the underlying
       
   297  * implementation uses <code>set()</code>, it might read March 3, 1999. A
       
   298  * better result would be February 28, 1999. Furthermore, if the user
       
   299  * presses the month increment button again, it should read March 31,
       
   300  * 1999, not March 28, 1999. By saving the original date and using either
       
   301  * <code>add()</code> or <code>roll()</code>, depending on whether larger
       
   302  * fields should be affected, the user interface can behave as most users
       
   303  * will intuitively expect.</p>
       
   304  *
       
   305  * @see          java.lang.System#currentTimeMillis()
       
   306  * @see          Date
       
   307  * @see          GregorianCalendar
       
   308  * @see          TimeZone
       
   309  * @see          java.text.DateFormat
       
   310  * @author Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu
       
   311  * @since 1.1
       
   312  */
       
   313 public abstract class Calendar implements Serializable, Cloneable, Comparable<Calendar> {
       
   314 
       
   315     // Data flow in Calendar
       
   316     // ---------------------
       
   317 
       
   318     // The current time is represented in two ways by Calendar: as UTC
       
   319     // milliseconds from the epoch (1 January 1970 0:00 UTC), and as local
       
   320     // fields such as MONTH, HOUR, AM_PM, etc.  It is possible to compute the
       
   321     // millis from the fields, and vice versa.  The data needed to do this
       
   322     // conversion is encapsulated by a TimeZone object owned by the Calendar.
       
   323     // The data provided by the TimeZone object may also be overridden if the
       
   324     // user sets the ZONE_OFFSET and/or DST_OFFSET fields directly. The class
       
   325     // keeps track of what information was most recently set by the caller, and
       
   326     // uses that to compute any other information as needed.
       
   327 
       
   328     // If the user sets the fields using set(), the data flow is as follows.
       
   329     // This is implemented by the Calendar subclass's computeTime() method.
       
   330     // During this process, certain fields may be ignored.  The disambiguation
       
   331     // algorithm for resolving which fields to pay attention to is described
       
   332     // in the class documentation.
       
   333 
       
   334     //   local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
       
   335     //           |
       
   336     //           | Using Calendar-specific algorithm
       
   337     //           V
       
   338     //   local standard millis
       
   339     //           |
       
   340     //           | Using TimeZone or user-set ZONE_OFFSET / DST_OFFSET
       
   341     //           V
       
   342     //   UTC millis (in time data member)
       
   343 
       
   344     // If the user sets the UTC millis using setTime() or setTimeInMillis(),
       
   345     // the data flow is as follows.  This is implemented by the Calendar
       
   346     // subclass's computeFields() method.
       
   347 
       
   348     //   UTC millis (in time data member)
       
   349     //           |
       
   350     //           | Using TimeZone getOffset()
       
   351     //           V
       
   352     //   local standard millis
       
   353     //           |
       
   354     //           | Using Calendar-specific algorithm
       
   355     //           V
       
   356     //   local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
       
   357 
       
   358     // In general, a round trip from fields, through local and UTC millis, and
       
   359     // back out to fields is made when necessary.  This is implemented by the
       
   360     // complete() method.  Resolving a partial set of fields into a UTC millis
       
   361     // value allows all remaining fields to be generated from that value.  If
       
   362     // the Calendar is lenient, the fields are also renormalized to standard
       
   363     // ranges when they are regenerated.
       
   364 
       
   365     /**
       
   366      * Field number for <code>get</code> and <code>set</code> indicating the
       
   367      * era, e.g., AD or BC in the Julian calendar. This is a calendar-specific
       
   368      * value; see subclass documentation.
       
   369      *
       
   370      * @see GregorianCalendar#AD
       
   371      * @see GregorianCalendar#BC
       
   372      */
       
   373     public final static int ERA = 0;
       
   374 
       
   375     /**
       
   376      * Field number for <code>get</code> and <code>set</code> indicating the
       
   377      * year. This is a calendar-specific value; see subclass documentation.
       
   378      */
       
   379     public final static int YEAR = 1;
       
   380 
       
   381     /**
       
   382      * Field number for <code>get</code> and <code>set</code> indicating the
       
   383      * month. This is a calendar-specific value. The first month of
       
   384      * the year in the Gregorian and Julian calendars is
       
   385      * <code>JANUARY</code> which is 0; the last depends on the number
       
   386      * of months in a year.
       
   387      *
       
   388      * @see #JANUARY
       
   389      * @see #FEBRUARY
       
   390      * @see #MARCH
       
   391      * @see #APRIL
       
   392      * @see #MAY
       
   393      * @see #JUNE
       
   394      * @see #JULY
       
   395      * @see #AUGUST
       
   396      * @see #SEPTEMBER
       
   397      * @see #OCTOBER
       
   398      * @see #NOVEMBER
       
   399      * @see #DECEMBER
       
   400      * @see #UNDECIMBER
       
   401      */
       
   402     public final static int MONTH = 2;
       
   403 
       
   404     /**
       
   405      * Field number for <code>get</code> and <code>set</code> indicating the
       
   406      * week number within the current year.  The first week of the year, as
       
   407      * defined by <code>getFirstDayOfWeek()</code> and
       
   408      * <code>getMinimalDaysInFirstWeek()</code>, has value 1.  Subclasses define
       
   409      * the value of <code>WEEK_OF_YEAR</code> for days before the first week of
       
   410      * the year.
       
   411      *
       
   412      * @see #getFirstDayOfWeek
       
   413      * @see #getMinimalDaysInFirstWeek
       
   414      */
       
   415     public final static int WEEK_OF_YEAR = 3;
       
   416 
       
   417     /**
       
   418      * Field number for <code>get</code> and <code>set</code> indicating the
       
   419      * week number within the current month.  The first week of the month, as
       
   420      * defined by <code>getFirstDayOfWeek()</code> and
       
   421      * <code>getMinimalDaysInFirstWeek()</code>, has value 1.  Subclasses define
       
   422      * the value of <code>WEEK_OF_MONTH</code> for days before the first week of
       
   423      * the month.
       
   424      *
       
   425      * @see #getFirstDayOfWeek
       
   426      * @see #getMinimalDaysInFirstWeek
       
   427      */
       
   428     public final static int WEEK_OF_MONTH = 4;
       
   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>DAY_OF_MONTH</code>.
       
   433      * The first day of the month has value 1.
       
   434      *
       
   435      * @see #DAY_OF_MONTH
       
   436      */
       
   437     public final static int DATE = 5;
       
   438 
       
   439     /**
       
   440      * Field number for <code>get</code> and <code>set</code> indicating the
       
   441      * day of the month. This is a synonym for <code>DATE</code>.
       
   442      * The first day of the month has value 1.
       
   443      *
       
   444      * @see #DATE
       
   445      */
       
   446     public final static int DAY_OF_MONTH = 5;
       
   447 
       
   448     /**
       
   449      * Field number for <code>get</code> and <code>set</code> indicating the day
       
   450      * number within the current year.  The first day of the year has value 1.
       
   451      */
       
   452     public final static int DAY_OF_YEAR = 6;
       
   453 
       
   454     /**
       
   455      * Field number for <code>get</code> and <code>set</code> indicating the day
       
   456      * of the week.  This field takes values <code>SUNDAY</code>,
       
   457      * <code>MONDAY</code>, <code>TUESDAY</code>, <code>WEDNESDAY</code>,
       
   458      * <code>THURSDAY</code>, <code>FRIDAY</code>, and <code>SATURDAY</code>.
       
   459      *
       
   460      * @see #SUNDAY
       
   461      * @see #MONDAY
       
   462      * @see #TUESDAY
       
   463      * @see #WEDNESDAY
       
   464      * @see #THURSDAY
       
   465      * @see #FRIDAY
       
   466      * @see #SATURDAY
       
   467      */
       
   468     public final static int DAY_OF_WEEK = 7;
       
   469 
       
   470     /**
       
   471      * Field number for <code>get</code> and <code>set</code> indicating the
       
   472      * ordinal number of the day of the week within the current month. Together
       
   473      * with the <code>DAY_OF_WEEK</code> field, this uniquely specifies a day
       
   474      * within a month.  Unlike <code>WEEK_OF_MONTH</code> and
       
   475      * <code>WEEK_OF_YEAR</code>, this field's value does <em>not</em> depend on
       
   476      * <code>getFirstDayOfWeek()</code> or
       
   477      * <code>getMinimalDaysInFirstWeek()</code>.  <code>DAY_OF_MONTH 1</code>
       
   478      * through <code>7</code> always correspond to <code>DAY_OF_WEEK_IN_MONTH
       
   479      * 1</code>; <code>8</code> through <code>14</code> correspond to
       
   480      * <code>DAY_OF_WEEK_IN_MONTH 2</code>, and so on.
       
   481      * <code>DAY_OF_WEEK_IN_MONTH 0</code> indicates the week before
       
   482      * <code>DAY_OF_WEEK_IN_MONTH 1</code>.  Negative values count back from the
       
   483      * end of the month, so the last Sunday of a month is specified as
       
   484      * <code>DAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1</code>.  Because
       
   485      * negative values count backward they will usually be aligned differently
       
   486      * within the month than positive values.  For example, if a month has 31
       
   487      * days, <code>DAY_OF_WEEK_IN_MONTH -1</code> will overlap
       
   488      * <code>DAY_OF_WEEK_IN_MONTH 5</code> and the end of <code>4</code>.
       
   489      *
       
   490      * @see #DAY_OF_WEEK
       
   491      * @see #WEEK_OF_MONTH
       
   492      */
       
   493     public final static int DAY_OF_WEEK_IN_MONTH = 8;
       
   494 
       
   495     /**
       
   496      * Field number for <code>get</code> and <code>set</code> indicating
       
   497      * whether the <code>HOUR</code> is before or after noon.
       
   498      * E.g., at 10:04:15.250 PM the <code>AM_PM</code> is <code>PM</code>.
       
   499      *
       
   500      * @see #AM
       
   501      * @see #PM
       
   502      * @see #HOUR
       
   503      */
       
   504     public final static int AM_PM = 9;
       
   505 
       
   506     /**
       
   507      * Field number for <code>get</code> and <code>set</code> indicating the
       
   508      * hour of the morning or afternoon. <code>HOUR</code> is used for the
       
   509      * 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12.
       
   510      * E.g., at 10:04:15.250 PM the <code>HOUR</code> is 10.
       
   511      *
       
   512      * @see #AM_PM
       
   513      * @see #HOUR_OF_DAY
       
   514      */
       
   515     public final static int HOUR = 10;
       
   516 
       
   517     /**
       
   518      * Field number for <code>get</code> and <code>set</code> indicating the
       
   519      * hour of the day. <code>HOUR_OF_DAY</code> is used for the 24-hour clock.
       
   520      * E.g., at 10:04:15.250 PM the <code>HOUR_OF_DAY</code> is 22.
       
   521      *
       
   522      * @see #HOUR
       
   523      */
       
   524     public final static int HOUR_OF_DAY = 11;
       
   525 
       
   526     /**
       
   527      * Field number for <code>get</code> and <code>set</code> indicating the
       
   528      * minute within the hour.
       
   529      * E.g., at 10:04:15.250 PM the <code>MINUTE</code> is 4.
       
   530      */
       
   531     public final static int MINUTE = 12;
       
   532 
       
   533     /**
       
   534      * Field number for <code>get</code> and <code>set</code> indicating the
       
   535      * second within the minute.
       
   536      * E.g., at 10:04:15.250 PM the <code>SECOND</code> is 15.
       
   537      */
       
   538     public final static int SECOND = 13;
       
   539 
       
   540     /**
       
   541      * Field number for <code>get</code> and <code>set</code> indicating the
       
   542      * millisecond within the second.
       
   543      * E.g., at 10:04:15.250 PM the <code>MILLISECOND</code> is 250.
       
   544      */
       
   545     public final static int MILLISECOND = 14;
       
   546 
       
   547     /**
       
   548      * Field number for <code>get</code> and <code>set</code>
       
   549      * indicating the raw offset from GMT in milliseconds.
       
   550      * <p>
       
   551      * This field reflects the correct GMT offset value of the time
       
   552      * zone of this <code>Calendar</code> if the
       
   553      * <code>TimeZone</code> implementation subclass supports
       
   554      * historical GMT offset changes.
       
   555      */
       
   556     public final static int ZONE_OFFSET = 15;
       
   557 
       
   558     /**
       
   559      * Field number for <code>get</code> and <code>set</code> indicating the
       
   560      * daylight saving offset in milliseconds.
       
   561      * <p>
       
   562      * This field reflects the correct daylight saving offset value of
       
   563      * the time zone of this <code>Calendar</code> if the
       
   564      * <code>TimeZone</code> implementation subclass supports
       
   565      * historical Daylight Saving Time schedule changes.
       
   566      */
       
   567     public final static int DST_OFFSET = 16;
       
   568 
       
   569     /**
       
   570      * The number of distinct fields recognized by <code>get</code> and <code>set</code>.
       
   571      * Field numbers range from <code>0..FIELD_COUNT-1</code>.
       
   572      */
       
   573     public final static int FIELD_COUNT = 17;
       
   574 
       
   575     /**
       
   576      * Value of the {@link #DAY_OF_WEEK} field indicating
       
   577      * Sunday.
       
   578      */
       
   579     public final static int SUNDAY = 1;
       
   580 
       
   581     /**
       
   582      * Value of the {@link #DAY_OF_WEEK} field indicating
       
   583      * Monday.
       
   584      */
       
   585     public final static int MONDAY = 2;
       
   586 
       
   587     /**
       
   588      * Value of the {@link #DAY_OF_WEEK} field indicating
       
   589      * Tuesday.
       
   590      */
       
   591     public final static int TUESDAY = 3;
       
   592 
       
   593     /**
       
   594      * Value of the {@link #DAY_OF_WEEK} field indicating
       
   595      * Wednesday.
       
   596      */
       
   597     public final static int WEDNESDAY = 4;
       
   598 
       
   599     /**
       
   600      * Value of the {@link #DAY_OF_WEEK} field indicating
       
   601      * Thursday.
       
   602      */
       
   603     public final static int THURSDAY = 5;
       
   604 
       
   605     /**
       
   606      * Value of the {@link #DAY_OF_WEEK} field indicating
       
   607      * Friday.
       
   608      */
       
   609     public final static int FRIDAY = 6;
       
   610 
       
   611     /**
       
   612      * Value of the {@link #DAY_OF_WEEK} field indicating
       
   613      * Saturday.
       
   614      */
       
   615     public final static int SATURDAY = 7;
       
   616 
       
   617     /**
       
   618      * Value of the {@link #MONTH} field indicating the
       
   619      * first month of the year in the Gregorian and Julian calendars.
       
   620      */
       
   621     public final static int JANUARY = 0;
       
   622 
       
   623     /**
       
   624      * Value of the {@link #MONTH} field indicating the
       
   625      * second month of the year in the Gregorian and Julian calendars.
       
   626      */
       
   627     public final static int FEBRUARY = 1;
       
   628 
       
   629     /**
       
   630      * Value of the {@link #MONTH} field indicating the
       
   631      * third month of the year in the Gregorian and Julian calendars.
       
   632      */
       
   633     public final static int MARCH = 2;
       
   634 
       
   635     /**
       
   636      * Value of the {@link #MONTH} field indicating the
       
   637      * fourth month of the year in the Gregorian and Julian calendars.
       
   638      */
       
   639     public final static int APRIL = 3;
       
   640 
       
   641     /**
       
   642      * Value of the {@link #MONTH} field indicating the
       
   643      * fifth month of the year in the Gregorian and Julian calendars.
       
   644      */
       
   645     public final static int MAY = 4;
       
   646 
       
   647     /**
       
   648      * Value of the {@link #MONTH} field indicating the
       
   649      * sixth month of the year in the Gregorian and Julian calendars.
       
   650      */
       
   651     public final static int JUNE = 5;
       
   652 
       
   653     /**
       
   654      * Value of the {@link #MONTH} field indicating the
       
   655      * seventh month of the year in the Gregorian and Julian calendars.
       
   656      */
       
   657     public final static int JULY = 6;
       
   658 
       
   659     /**
       
   660      * Value of the {@link #MONTH} field indicating the
       
   661      * eighth month of the year in the Gregorian and Julian calendars.
       
   662      */
       
   663     public final static int AUGUST = 7;
       
   664 
       
   665     /**
       
   666      * Value of the {@link #MONTH} field indicating the
       
   667      * ninth month of the year in the Gregorian and Julian calendars.
       
   668      */
       
   669     public final static int SEPTEMBER = 8;
       
   670 
       
   671     /**
       
   672      * Value of the {@link #MONTH} field indicating the
       
   673      * tenth month of the year in the Gregorian and Julian calendars.
       
   674      */
       
   675     public final static int OCTOBER = 9;
       
   676 
       
   677     /**
       
   678      * Value of the {@link #MONTH} field indicating the
       
   679      * eleventh month of the year in the Gregorian and Julian calendars.
       
   680      */
       
   681     public final static int NOVEMBER = 10;
       
   682 
       
   683     /**
       
   684      * Value of the {@link #MONTH} field indicating the
       
   685      * twelfth month of the year in the Gregorian and Julian calendars.
       
   686      */
       
   687     public final static int DECEMBER = 11;
       
   688 
       
   689     /**
       
   690      * Value of the {@link #MONTH} field indicating the
       
   691      * thirteenth month of the year. Although <code>GregorianCalendar</code>
       
   692      * does not use this value, lunar calendars do.
       
   693      */
       
   694     public final static int UNDECIMBER = 12;
       
   695 
       
   696     /**
       
   697      * Value of the {@link #AM_PM} field indicating the
       
   698      * period of the day from midnight to just before noon.
       
   699      */
       
   700     public final static int AM = 0;
       
   701 
       
   702     /**
       
   703      * Value of the {@link #AM_PM} field indicating the
       
   704      * period of the day from noon to just before midnight.
       
   705      */
       
   706     public final static int PM = 1;
       
   707 
       
   708     /**
       
   709      * A style specifier for {@link #getDisplayNames(int, int, Locale)
       
   710      * getDisplayNames} indicating names in all styles, such as
       
   711      * "January" and "Jan".
       
   712      *
       
   713      * @see #SHORT_FORMAT
       
   714      * @see #LONG_FORMAT
       
   715      * @see #SHORT_STANDALONE
       
   716      * @see #LONG_STANDALONE
       
   717      * @see #SHORT
       
   718      * @see #LONG
       
   719      * @since 1.6
       
   720      */
       
   721     public static final int ALL_STYLES = 0;
       
   722 
       
   723     static final int STANDALONE_MASK = 0x8000;
       
   724 
       
   725     /**
       
   726      * A style specifier for {@link #getDisplayName(int, int, Locale)
       
   727      * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
       
   728      * getDisplayNames} equivalent to {@link #SHORT_FORMAT}.
       
   729      *
       
   730      * @see #SHORT_STANDALONE
       
   731      * @see #LONG
       
   732      * @since 1.6
       
   733      */
       
   734     public static final int SHORT = 1;
       
   735 
       
   736     /**
       
   737      * A style specifier for {@link #getDisplayName(int, int, Locale)
       
   738      * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
       
   739      * getDisplayNames} equivalent to {@link #LONG_FORMAT}.
       
   740      *
       
   741      * @see #LONG_STANDALONE
       
   742      * @see #SHORT
       
   743      * @since 1.6
       
   744      */
       
   745     public static final int LONG = 2;
       
   746 
       
   747     /**
       
   748      * A style specifier for {@link #getDisplayName(int, int, Locale)
       
   749      * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
       
   750      * getDisplayNames} indicating a narrow name used for format. Narrow names
       
   751      * are typically single character strings, such as "M" for Monday.
       
   752      *
       
   753      * @see #NARROW_STANDALONE
       
   754      * @see #SHORT_FORMAT
       
   755      * @see #LONG_FORMAT
       
   756      * @since 1.8
       
   757      */
       
   758     public static final int NARROW_FORMAT = 4;
       
   759 
       
   760     /**
       
   761      * A style specifier for {@link #getDisplayName(int, int, Locale)
       
   762      * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
       
   763      * getDisplayNames} indicating a narrow name independently. Narrow names
       
   764      * are typically single character strings, such as "M" for Monday.
       
   765      *
       
   766      * @see #NARROW_FORMAT
       
   767      * @see #SHORT_STANDALONE
       
   768      * @see #LONG_STANDALONE
       
   769      * @since 1.8
       
   770      */
       
   771     public static final int NARROW_STANDALONE = NARROW_FORMAT | STANDALONE_MASK;
       
   772 
       
   773     /**
       
   774      * A style specifier for {@link #getDisplayName(int, int, Locale)
       
   775      * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
       
   776      * getDisplayNames} indicating a short name used for format.
       
   777      *
       
   778      * @see #SHORT_STANDALONE
       
   779      * @see #LONG_FORMAT
       
   780      * @see #LONG_STANDALONE
       
   781      * @since 1.8
       
   782      */
       
   783     public static final int SHORT_FORMAT = 1;
       
   784 
       
   785     /**
       
   786      * A style specifier for {@link #getDisplayName(int, int, Locale)
       
   787      * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
       
   788      * getDisplayNames} indicating a long name used for format.
       
   789      *
       
   790      * @see #LONG_STANDALONE
       
   791      * @see #SHORT_FORMAT
       
   792      * @see #SHORT_STANDALONE
       
   793      * @since 1.8
       
   794      */
       
   795     public static final int LONG_FORMAT = 2;
       
   796 
       
   797     /**
       
   798      * A style specifier for {@link #getDisplayName(int, int, Locale)
       
   799      * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
       
   800      * getDisplayNames} indicating a short name used independently,
       
   801      * such as a month abbreviation as calendar headers.
       
   802      *
       
   803      * @see #SHORT_FORMAT
       
   804      * @see #LONG_FORMAT
       
   805      * @see #LONG_STANDALONE
       
   806      * @since 1.8
       
   807      */
       
   808     public static final int SHORT_STANDALONE = SHORT | STANDALONE_MASK;
       
   809 
       
   810     /**
       
   811      * A style specifier for {@link #getDisplayName(int, int, Locale)
       
   812      * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
       
   813      * getDisplayNames} indicating a long name used independently,
       
   814      * such as a month name as calendar headers.
       
   815      *
       
   816      * @see #LONG_FORMAT
       
   817      * @see #SHORT_FORMAT
       
   818      * @see #SHORT_STANDALONE
       
   819      * @since 1.8
       
   820      */
       
   821     public static final int LONG_STANDALONE = LONG | STANDALONE_MASK;
       
   822 
       
   823     // Internal notes:
       
   824     // Calendar contains two kinds of time representations: current "time" in
       
   825     // milliseconds, and a set of calendar "fields" representing the current time.
       
   826     // The two representations are usually in sync, but can get out of sync
       
   827     // as follows.
       
   828     // 1. Initially, no fields are set, and the time is invalid.
       
   829     // 2. If the time is set, all fields are computed and in sync.
       
   830     // 3. If a single field is set, the time is invalid.
       
   831     // Recomputation of the time and fields happens when the object needs
       
   832     // to return a result to the user, or use a result for a computation.
       
   833 
       
   834     /**
       
   835      * The calendar field values for the currently set time for this calendar.
       
   836      * This is an array of <code>FIELD_COUNT</code> integers, with index values
       
   837      * <code>ERA</code> through <code>DST_OFFSET</code>.
       
   838      * @serial
       
   839      */
       
   840     @SuppressWarnings("ProtectedField")
       
   841     protected int           fields[];
       
   842 
       
   843     /**
       
   844      * The flags which tell if a specified calendar field for the calendar is set.
       
   845      * A new object has no fields set.  After the first call to a method
       
   846      * which generates the fields, they all remain set after that.
       
   847      * This is an array of <code>FIELD_COUNT</code> booleans, with index values
       
   848      * <code>ERA</code> through <code>DST_OFFSET</code>.
       
   849      * @serial
       
   850      */
       
   851     @SuppressWarnings("ProtectedField")
       
   852     protected boolean       isSet[];
       
   853 
       
   854     /**
       
   855      * Pseudo-time-stamps which specify when each field was set. There
       
   856      * are two special values, UNSET and COMPUTED. Values from
       
   857      * MINIMUM_USER_SET to Integer.MAX_VALUE are legal user set values.
       
   858      */
       
   859     transient private int   stamp[];
       
   860 
       
   861     /**
       
   862      * The currently set time for this calendar, expressed in milliseconds after
       
   863      * January 1, 1970, 0:00:00 GMT.
       
   864      * @see #isTimeSet
       
   865      * @serial
       
   866      */
       
   867     @SuppressWarnings("ProtectedField")
       
   868     protected long          time;
       
   869 
       
   870     /**
       
   871      * True if then the value of <code>time</code> is valid.
       
   872      * The time is made invalid by a change to an item of <code>field[]</code>.
       
   873      * @see #time
       
   874      * @serial
       
   875      */
       
   876     @SuppressWarnings("ProtectedField")
       
   877     protected boolean       isTimeSet;
       
   878 
       
   879     /**
       
   880      * True if <code>fields[]</code> are in sync with the currently set time.
       
   881      * If false, then the next attempt to get the value of a field will
       
   882      * force a recomputation of all fields from the current value of
       
   883      * <code>time</code>.
       
   884      * @serial
       
   885      */
       
   886     @SuppressWarnings("ProtectedField")
       
   887     protected boolean       areFieldsSet;
       
   888 
       
   889     /**
       
   890      * True if all fields have been set.
       
   891      * @serial
       
   892      */
       
   893     transient boolean       areAllFieldsSet;
       
   894 
       
   895     /**
       
   896      * <code>True</code> if this calendar allows out-of-range field values during computation
       
   897      * of <code>time</code> from <code>fields[]</code>.
       
   898      * @see #setLenient
       
   899      * @see #isLenient
       
   900      * @serial
       
   901      */
       
   902     private boolean         lenient = true;
       
   903 
       
   904     /**
       
   905      * The <code>TimeZone</code> used by this calendar. <code>Calendar</code>
       
   906      * uses the time zone data to translate between locale and GMT time.
       
   907      * @serial
       
   908      */
       
   909     private TimeZone        zone;
       
   910 
       
   911     /**
       
   912      * <code>True</code> if zone references to a shared TimeZone object.
       
   913      */
       
   914     transient private boolean sharedZone = false;
       
   915 
       
   916     /**
       
   917      * The first day of the week, with possible values <code>SUNDAY</code>,
       
   918      * <code>MONDAY</code>, etc.  This is a locale-dependent value.
       
   919      * @serial
       
   920      */
       
   921     private int             firstDayOfWeek;
       
   922 
       
   923     /**
       
   924      * The number of days required for the first week in a month or year,
       
   925      * with possible values from 1 to 7.  This is a locale-dependent value.
       
   926      * @serial
       
   927      */
       
   928     private int             minimalDaysInFirstWeek;
       
   929 
       
   930     /**
       
   931      * Cache to hold the firstDayOfWeek and minimalDaysInFirstWeek
       
   932      * of a Locale.
       
   933      */
       
   934     private static final ConcurrentMap<Locale, int[]> cachedLocaleData
       
   935         = new ConcurrentHashMap<>(3);
       
   936 
       
   937     // Special values of stamp[]
       
   938     /**
       
   939      * The corresponding fields[] has no value.
       
   940      */
       
   941     private static final int        UNSET = 0;
       
   942 
       
   943     /**
       
   944      * The value of the corresponding fields[] has been calculated internally.
       
   945      */
       
   946     private static final int        COMPUTED = 1;
       
   947 
       
   948     /**
       
   949      * The value of the corresponding fields[] has been set externally. Stamp
       
   950      * values which are greater than 1 represents the (pseudo) time when the
       
   951      * corresponding fields[] value was set.
       
   952      */
       
   953     private static final int        MINIMUM_USER_STAMP = 2;
       
   954 
       
   955     /**
       
   956      * The mask value that represents all of the fields.
       
   957      */
       
   958     static final int ALL_FIELDS = (1 << FIELD_COUNT) - 1;
       
   959 
       
   960     /**
       
   961      * The next available value for <code>stamp[]</code>, an internal array.
       
   962      * This actually should not be written out to the stream, and will probably
       
   963      * be removed from the stream in the near future.  In the meantime,
       
   964      * a value of <code>MINIMUM_USER_STAMP</code> should be used.
       
   965      * @serial
       
   966      */
       
   967     private int             nextStamp = MINIMUM_USER_STAMP;
       
   968 
       
   969     // the internal serial version which says which version was written
       
   970     // - 0 (default) for version up to JDK 1.1.5
       
   971     // - 1 for version from JDK 1.1.6, which writes a correct 'time' value
       
   972     //     as well as compatible values for other fields.  This is a
       
   973     //     transitional format.
       
   974     // - 2 (not implemented yet) a future version, in which fields[],
       
   975     //     areFieldsSet, and isTimeSet become transient, and isSet[] is
       
   976     //     removed. In JDK 1.1.6 we write a format compatible with version 2.
       
   977     static final int        currentSerialVersion = 1;
       
   978 
       
   979     /**
       
   980      * The version of the serialized data on the stream.  Possible values:
       
   981      * <dl>
       
   982      * <dt><b>0</b> or not present on stream</dt>
       
   983      * <dd>
       
   984      * JDK 1.1.5 or earlier.
       
   985      * </dd>
       
   986      * <dt><b>1</b></dt>
       
   987      * <dd>
       
   988      * JDK 1.1.6 or later.  Writes a correct 'time' value
       
   989      * as well as compatible values for other fields.  This is a
       
   990      * transitional format.
       
   991      * </dd>
       
   992      * </dl>
       
   993      * When streaming out this class, the most recent format
       
   994      * and the highest allowable <code>serialVersionOnStream</code>
       
   995      * is written.
       
   996      * @serial
       
   997      * @since 1.1.6
       
   998      */
       
   999     private int             serialVersionOnStream = currentSerialVersion;
       
  1000 
       
  1001     // Proclaim serialization compatibility with JDK 1.1
       
  1002     static final long       serialVersionUID = -1807547505821590642L;
       
  1003 
       
  1004     // Mask values for calendar fields
       
  1005     @SuppressWarnings("PointlessBitwiseExpression")
       
  1006     final static int ERA_MASK           = (1 << ERA);
       
  1007     final static int YEAR_MASK          = (1 << YEAR);
       
  1008     final static int MONTH_MASK         = (1 << MONTH);
       
  1009     final static int WEEK_OF_YEAR_MASK  = (1 << WEEK_OF_YEAR);
       
  1010     final static int WEEK_OF_MONTH_MASK = (1 << WEEK_OF_MONTH);
       
  1011     final static int DAY_OF_MONTH_MASK  = (1 << DAY_OF_MONTH);
       
  1012     final static int DATE_MASK          = DAY_OF_MONTH_MASK;
       
  1013     final static int DAY_OF_YEAR_MASK   = (1 << DAY_OF_YEAR);
       
  1014     final static int DAY_OF_WEEK_MASK   = (1 << DAY_OF_WEEK);
       
  1015     final static int DAY_OF_WEEK_IN_MONTH_MASK  = (1 << DAY_OF_WEEK_IN_MONTH);
       
  1016     final static int AM_PM_MASK         = (1 << AM_PM);
       
  1017     final static int HOUR_MASK          = (1 << HOUR);
       
  1018     final static int HOUR_OF_DAY_MASK   = (1 << HOUR_OF_DAY);
       
  1019     final static int MINUTE_MASK        = (1 << MINUTE);
       
  1020     final static int SECOND_MASK        = (1 << SECOND);
       
  1021     final static int MILLISECOND_MASK   = (1 << MILLISECOND);
       
  1022     final static int ZONE_OFFSET_MASK   = (1 << ZONE_OFFSET);
       
  1023     final static int DST_OFFSET_MASK    = (1 << DST_OFFSET);
       
  1024 
       
  1025     /**
       
  1026      * {@code Calendar.Builder} is used for creating a {@code Calendar} from
       
  1027      * various date-time parameters.
       
  1028      *
       
  1029      * <p>There are two ways to set a {@code Calendar} to a date-time value. One
       
  1030      * is to set the instant parameter to a millisecond offset from the <a
       
  1031      * href="Calendar.html#Epoch">Epoch</a>. The other is to set individual
       
  1032      * field parameters, such as {@link Calendar#YEAR YEAR}, to their desired
       
  1033      * values. These two ways can't be mixed. Trying to set both the instant and
       
  1034      * individual fields will cause an {@link IllegalStateException} to be
       
  1035      * thrown. However, it is permitted to override previous values of the
       
  1036      * instant or field parameters.
       
  1037      *
       
  1038      * <p>If no enough field parameters are given for determining date and/or
       
  1039      * time, calendar specific default values are used when building a
       
  1040      * {@code Calendar}. For example, if the {@link Calendar#YEAR YEAR} value
       
  1041      * isn't given for the Gregorian calendar, 1970 will be used. If there are
       
  1042      * any conflicts among field parameters, the <a
       
  1043      * href="Calendar.html#resolution"> resolution rules</a> are applied.
       
  1044      * Therefore, the order of field setting matters.
       
  1045      *
       
  1046      * <p>In addition to the date-time parameters,
       
  1047      * the {@linkplain #setLocale(Locale) locale},
       
  1048      * {@linkplain #setTimeZone(TimeZone) time zone},
       
  1049      * {@linkplain #setWeekDefinition(int, int) week definition}, and
       
  1050      * {@linkplain #setLenient(boolean) leniency mode} parameters can be set.
       
  1051      *
       
  1052      * <p><b>Examples</b>
       
  1053      * <p>The following are sample usages. Sample code assumes that the
       
  1054      * {@code Calendar} constants are statically imported.
       
  1055      *
       
  1056      * <p>The following code produces a {@code Calendar} with date 2012-12-31
       
  1057      * (Gregorian) because Monday is the first day of a week with the <a
       
  1058      * href="GregorianCalendar.html#iso8601_compatible_setting"> ISO 8601
       
  1059      * compatible week parameters</a>.
       
  1060      * <pre>
       
  1061      *   Calendar cal = new Calendar.Builder().setCalendarType("iso8601")
       
  1062      *                        .setWeekDate(2013, 1, MONDAY).build();</pre>
       
  1063      * <p>The following code produces a Japanese {@code Calendar} with date
       
  1064      * 1989-01-08 (Gregorian), assuming that the default {@link Calendar#ERA ERA}
       
  1065      * is <em>Heisei</em> that started on that day.
       
  1066      * <pre>
       
  1067      *   Calendar cal = new Calendar.Builder().setCalendarType("japanese")
       
  1068      *                        .setFields(YEAR, 1, DAY_OF_YEAR, 1).build();</pre>
       
  1069      *
       
  1070      * @since 1.8
       
  1071      * @see Calendar#getInstance(TimeZone, Locale)
       
  1072      * @see Calendar#fields
       
  1073      */
       
  1074     public static class Builder {
       
  1075         private static final int NFIELDS = FIELD_COUNT + 1; // +1 for WEEK_YEAR
       
  1076         private static final int WEEK_YEAR = FIELD_COUNT;
       
  1077 
       
  1078         private long instant;
       
  1079         // Calendar.stamp[] (lower half) and Calendar.fields[] (upper half) combined
       
  1080         private int[] fields;
       
  1081         // Pseudo timestamp starting from MINIMUM_USER_STAMP.
       
  1082         // (COMPUTED is used to indicate that the instant has been set.)
       
  1083         private int nextStamp;
       
  1084         // maxFieldIndex keeps the max index of fields which have been set.
       
  1085         // (WEEK_YEAR is never included.)
       
  1086         private int maxFieldIndex;
       
  1087         private String type;
       
  1088         private TimeZone zone;
       
  1089         private boolean lenient = true;
       
  1090         private Locale locale;
       
  1091         private int firstDayOfWeek, minimalDaysInFirstWeek;
       
  1092 
       
  1093         /**
       
  1094          * Constructs a {@code Calendar.Builder}.
       
  1095          */
       
  1096         public Builder() {
       
  1097         }
       
  1098 
       
  1099         /**
       
  1100          * Sets the instant parameter to the given {@code instant} value that is
       
  1101          * a millisecond offset from <a href="Calendar.html#Epoch">the
       
  1102          * Epoch</a>.
       
  1103          *
       
  1104          * @param instant a millisecond offset from the Epoch
       
  1105          * @return this {@code Calendar.Builder}
       
  1106          * @throws IllegalStateException if any of the field parameters have
       
  1107          *                               already been set
       
  1108          * @see Calendar#setTime(Date)
       
  1109          * @see Calendar#setTimeInMillis(long)
       
  1110          * @see Calendar#time
       
  1111          */
       
  1112         public Builder setInstant(long instant) {
       
  1113             if (fields != null) {
       
  1114                 throw new IllegalStateException();
       
  1115             }
       
  1116             this.instant = instant;
       
  1117             nextStamp = COMPUTED;
       
  1118             return this;
       
  1119         }
       
  1120 
       
  1121         /**
       
  1122          * Sets the instant parameter to the {@code instant} value given by a
       
  1123          * {@link Date}. This method is equivalent to a call to
       
  1124          * {@link #setInstant(long) setInstant(instant.getTime())}.
       
  1125          *
       
  1126          * @param instant a {@code Date} representing a millisecond offset from
       
  1127          *                the Epoch
       
  1128          * @return this {@code Calendar.Builder}
       
  1129          * @throws NullPointerException  if {@code instant} is {@code null}
       
  1130          * @throws IllegalStateException if any of the field parameters have
       
  1131          *                               already been set
       
  1132          * @see Calendar#setTime(Date)
       
  1133          * @see Calendar#setTimeInMillis(long)
       
  1134          * @see Calendar#time
       
  1135          */
       
  1136         public Builder setInstant(Date instant) {
       
  1137             return setInstant(instant.getTime()); // NPE if instant == null
       
  1138         }
       
  1139 
       
  1140         /**
       
  1141          * Sets the {@code field} parameter to the given {@code value}.
       
  1142          * {@code field} is an index to the {@link Calendar#fields}, such as
       
  1143          * {@link Calendar#DAY_OF_MONTH DAY_OF_MONTH}. Field value validation is
       
  1144          * not performed in this method. Any out of range values are either
       
  1145          * normalized in lenient mode or detected as an invalid value in
       
  1146          * non-lenient mode when building a {@code Calendar}.
       
  1147          *
       
  1148          * @param field an index to the {@code Calendar} fields
       
  1149          * @param value the field value
       
  1150          * @return this {@code Calendar.Builder}
       
  1151          * @throws IllegalArgumentException if {@code field} is invalid
       
  1152          * @throws IllegalStateException if the instant value has already been set,
       
  1153          *                      or if fields have been set too many
       
  1154          *                      (approximately {@link Integer#MAX_VALUE}) times.
       
  1155          * @see Calendar#set(int, int)
       
  1156          */
       
  1157         public Builder set(int field, int value) {
       
  1158             // Note: WEEK_YEAR can't be set with this method.
       
  1159             if (field < 0 || field >= FIELD_COUNT) {
       
  1160                 throw new IllegalArgumentException("field is invalid");
       
  1161             }
       
  1162             if (isInstantSet()) {
       
  1163                 throw new IllegalStateException("instant has been set");
       
  1164             }
       
  1165             allocateFields();
       
  1166             internalSet(field, value);
       
  1167             return this;
       
  1168         }
       
  1169 
       
  1170         /**
       
  1171          * Sets field parameters to their values given by
       
  1172          * {@code fieldValuePairs} that are pairs of a field and its value.
       
  1173          * For example,
       
  1174          * <pre>
       
  1175          *   setFeilds(Calendar.YEAR, 2013,
       
  1176          *             Calendar.MONTH, Calendar.DECEMBER,
       
  1177          *             Calendar.DAY_OF_MONTH, 23);</pre>
       
  1178          * is equivalent to the sequence of the following
       
  1179          * {@link #set(int, int) set} calls:
       
  1180          * <pre>
       
  1181          *   set(Calendar.YEAR, 2013)
       
  1182          *   .set(Calendar.MONTH, Calendar.DECEMBER)
       
  1183          *   .set(Calendar.DAY_OF_MONTH, 23);</pre>
       
  1184          *
       
  1185          * @param fieldValuePairs field-value pairs
       
  1186          * @return this {@code Calendar.Builder}
       
  1187          * @throws NullPointerException if {@code fieldValuePairs} is {@code null}
       
  1188          * @throws IllegalArgumentException if any of fields are invalid,
       
  1189          *             or if {@code fieldValuePairs.length} is an odd number.
       
  1190          * @throws IllegalStateException    if the instant value has been set,
       
  1191          *             or if fields have been set too many (approximately
       
  1192          *             {@link Integer#MAX_VALUE}) times.
       
  1193          */
       
  1194         public Builder setFields(int... fieldValuePairs) {
       
  1195             int len = fieldValuePairs.length;
       
  1196             if ((len % 2) != 0) {
       
  1197                 throw new IllegalArgumentException();
       
  1198             }
       
  1199             if (isInstantSet()) {
       
  1200                 throw new IllegalStateException("instant has been set");
       
  1201             }
       
  1202             if ((nextStamp + len / 2) < 0) {
       
  1203                 throw new IllegalStateException("stamp counter overflow");
       
  1204             }
       
  1205             allocateFields();
       
  1206             for (int i = 0; i < len; ) {
       
  1207                 int field = fieldValuePairs[i++];
       
  1208                 // Note: WEEK_YEAR can't be set with this method.
       
  1209                 if (field < 0 || field >= FIELD_COUNT) {
       
  1210                     throw new IllegalArgumentException("field is invalid");
       
  1211                 }
       
  1212                 internalSet(field, fieldValuePairs[i++]);
       
  1213             }
       
  1214             return this;
       
  1215         }
       
  1216 
       
  1217         /**
       
  1218          * Sets the date field parameters to the values given by {@code year},
       
  1219          * {@code month}, and {@code dayOfMonth}. This method is equivalent to
       
  1220          * a call to:
       
  1221          * <pre>
       
  1222          *   setFields(Calendar.YEAR, year,
       
  1223          *             Calendar.MONTH, month,
       
  1224          *             Calendar.DAY_OF_MONTH, dayOfMonth);</pre>
       
  1225          *
       
  1226          * @param year       the {@link Calendar#YEAR YEAR} value
       
  1227          * @param month      the {@link Calendar#MONTH MONTH} value
       
  1228          *                   (the month numbering is <em>0-based</em>).
       
  1229          * @param dayOfMonth the {@link Calendar#DAY_OF_MONTH DAY_OF_MONTH} value
       
  1230          * @return this {@code Calendar.Builder}
       
  1231          */
       
  1232         public Builder setDate(int year, int month, int dayOfMonth) {
       
  1233             return setFields(YEAR, year, MONTH, month, DAY_OF_MONTH, dayOfMonth);
       
  1234         }
       
  1235 
       
  1236         /**
       
  1237          * Sets the time of day field parameters to the values given by
       
  1238          * {@code hourOfDay}, {@code minute}, and {@code second}. This method is
       
  1239          * equivalent to a call to:
       
  1240          * <pre>
       
  1241          *   setTimeOfDay(hourOfDay, minute, second, 0);</pre>
       
  1242          *
       
  1243          * @param hourOfDay the {@link Calendar#HOUR_OF_DAY HOUR_OF_DAY} value
       
  1244          *                  (24-hour clock)
       
  1245          * @param minute    the {@link Calendar#MINUTE MINUTE} value
       
  1246          * @param second    the {@link Calendar#SECOND SECOND} value
       
  1247          * @return this {@code Calendar.Builder}
       
  1248          */
       
  1249         public Builder setTimeOfDay(int hourOfDay, int minute, int second) {
       
  1250             return setTimeOfDay(hourOfDay, minute, second, 0);
       
  1251         }
       
  1252 
       
  1253         /**
       
  1254          * Sets the time of day field parameters to the values given by
       
  1255          * {@code hourOfDay}, {@code minute}, {@code second}, and
       
  1256          * {@code millis}. This method is equivalent to a call to:
       
  1257          * <pre>
       
  1258          *   setFields(Calendar.HOUR_OF_DAY, hourOfDay,
       
  1259          *             Calendar.MINUTE, minute,
       
  1260          *             Calendar.SECOND, second,
       
  1261          *             Calendar.MILLISECOND, millis);</pre>
       
  1262          *
       
  1263          * @param hourOfDay the {@link Calendar#HOUR_OF_DAY HOUR_OF_DAY} value
       
  1264          *                  (24-hour clock)
       
  1265          * @param minute    the {@link Calendar#MINUTE MINUTE} value
       
  1266          * @param second    the {@link Calendar#SECOND SECOND} value
       
  1267          * @param millis    the {@link Calendar#MILLISECOND MILLISECOND} value
       
  1268          * @return this {@code Calendar.Builder}
       
  1269          */
       
  1270         public Builder setTimeOfDay(int hourOfDay, int minute, int second, int millis) {
       
  1271             return setFields(HOUR_OF_DAY, hourOfDay, MINUTE, minute,
       
  1272                              SECOND, second, MILLISECOND, millis);
       
  1273         }
       
  1274 
       
  1275         /**
       
  1276          * Sets the week-based date parameters to the values with the given
       
  1277          * date specifiers - week year, week of year, and day of week.
       
  1278          *
       
  1279          * <p>If the specified calendar doesn't support week dates, the
       
  1280          * {@link #build() build} method will throw an {@link IllegalArgumentException}.
       
  1281          *
       
  1282          * @param weekYear   the week year
       
  1283          * @param weekOfYear the week number based on {@code weekYear}
       
  1284          * @param dayOfWeek  the day of week value: one of the constants
       
  1285          *     for the {@link Calendar#DAY_OF_WEEK DAY_OF_WEEK} field:
       
  1286          *     {@link Calendar#SUNDAY SUNDAY}, ..., {@link Calendar#SATURDAY SATURDAY}.
       
  1287          * @return this {@code Calendar.Builder}
       
  1288          * @see Calendar#setWeekDate(int, int, int)
       
  1289          * @see Calendar#isWeekDateSupported()
       
  1290          */
       
  1291         public Builder setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) {
       
  1292             allocateFields();
       
  1293             internalSet(WEEK_YEAR, weekYear);
       
  1294             internalSet(WEEK_OF_YEAR, weekOfYear);
       
  1295             internalSet(DAY_OF_WEEK, dayOfWeek);
       
  1296             return this;
       
  1297         }
       
  1298 
       
  1299         /**
       
  1300          * Sets the time zone parameter to the given {@code zone}. If no time
       
  1301          * zone parameter is given to this {@code Caledar.Builder}, the
       
  1302          * {@linkplain TimeZone#getDefault() default
       
  1303          * <code>TimeZone</code>} will be used in the {@link #build() build}
       
  1304          * method.
       
  1305          *
       
  1306          * @param zone the {@link TimeZone}
       
  1307          * @return this {@code Calendar.Builder}
       
  1308          * @throws NullPointerException if {@code zone} is {@code null}
       
  1309          * @see Calendar#setTimeZone(TimeZone)
       
  1310          */
       
  1311         public Builder setTimeZone(TimeZone zone) {
       
  1312             if (zone == null) {
       
  1313                 throw new NullPointerException();
       
  1314             }
       
  1315             this.zone = zone;
       
  1316             return this;
       
  1317         }
       
  1318 
       
  1319         /**
       
  1320          * Sets the lenient mode parameter to the value given by {@code lenient}.
       
  1321          * If no lenient parameter is given to this {@code Calendar.Builder},
       
  1322          * lenient mode will be used in the {@link #build() build} method.
       
  1323          *
       
  1324          * @param lenient {@code true} for lenient mode;
       
  1325          *                {@code false} for non-lenient mode
       
  1326          * @return this {@code Calendar.Builder}
       
  1327          * @see Calendar#setLenient(boolean)
       
  1328          */
       
  1329         public Builder setLenient(boolean lenient) {
       
  1330             this.lenient = lenient;
       
  1331             return this;
       
  1332         }
       
  1333 
       
  1334         /**
       
  1335          * Sets the calendar type parameter to the given {@code type}. The
       
  1336          * calendar type given by this method has precedence over any explicit
       
  1337          * or implicit calendar type given by the
       
  1338          * {@linkplain #setLocale(Locale) locale}.
       
  1339          *
       
  1340          * <p>In addition to the available calendar types returned by the
       
  1341          * {@link Calendar#getAvailableCalendarTypes() Calendar.getAvailableCalendarTypes}
       
  1342          * method, {@code "gregorian"} and {@code "iso8601"} as aliases of
       
  1343          * {@code "gregory"} can be used with this method.
       
  1344          *
       
  1345          * @param type the calendar type
       
  1346          * @return this {@code Calendar.Builder}
       
  1347          * @throws NullPointerException if {@code type} is {@code null}
       
  1348          * @throws IllegalArgumentException if {@code type} is unknown
       
  1349          * @throws IllegalStateException if another calendar type has already been set
       
  1350          * @see Calendar#getCalendarType()
       
  1351          * @see Calendar#getAvailableCalendarTypes()
       
  1352          */
       
  1353         public Builder setCalendarType(String type) {
       
  1354             if (type.equals("gregorian")) { // NPE if type == null
       
  1355                 type = "gregory";
       
  1356             }
       
  1357             if (!Calendar.getAvailableCalendarTypes().contains(type)
       
  1358                     && !type.equals("iso8601")) {
       
  1359                 throw new IllegalArgumentException("unknown calendar type: " + type);
       
  1360             }
       
  1361             if (this.type == null) {
       
  1362                 this.type = type;
       
  1363             } else {
       
  1364                 if (!this.type.equals(type)) {
       
  1365                     throw new IllegalStateException("calendar type override");
       
  1366                 }
       
  1367             }
       
  1368             return this;
       
  1369         }
       
  1370 
       
  1371         /**
       
  1372          * Sets the locale parameter to the given {@code locale}. If no locale
       
  1373          * is given to this {@code Calendar.Builder}, the {@linkplain
       
  1374          * Locale#getDefault(Locale.Category) default <code>Locale</code>}
       
  1375          * for {@link Locale.Category#FORMAT} will be used.
       
  1376          *
       
  1377          * <p>If no calendar type is explicitly given by a call to the
       
  1378          * {@link #setCalendarType(String) setCalendarType} method,
       
  1379          * the {@code Locale} value is used to determine what type of
       
  1380          * {@code Calendar} to be built.
       
  1381          *
       
  1382          * <p>If no week definition parameters are explicitly given by a call to
       
  1383          * the {@link #setWeekDefinition(int,int) setWeekDefinition} method, the
       
  1384          * {@code Locale}'s default values are used.
       
  1385          *
       
  1386          * @param locale the {@link Locale}
       
  1387          * @throws NullPointerException if {@code locale} is {@code null}
       
  1388          * @return this {@code Calendar.Builder}
       
  1389          * @see Calendar#getInstance(Locale)
       
  1390          */
       
  1391         public Builder setLocale(Locale locale) {
       
  1392             if (locale == null) {
       
  1393                 throw new NullPointerException();
       
  1394             }
       
  1395             this.locale = locale;
       
  1396             return this;
       
  1397         }
       
  1398 
       
  1399         /**
       
  1400          * Sets the week definition parameters to the values given by
       
  1401          * {@code firstDayOfWeek} and {@code minimalDaysInFirstWeek} that are
       
  1402          * used to determine the <a href="Calendar.html#First_Week">first
       
  1403          * week</a> of a year. The parameters given by this method have
       
  1404          * precedence over the default values given by the
       
  1405          * {@linkplain #setLocale(Locale) locale}.
       
  1406          *
       
  1407          * @param firstDayOfWeek the first day of a week; one of
       
  1408          *                       {@link Calendar#SUNDAY} to {@link Calendar#SATURDAY}
       
  1409          * @param minimalDaysInFirstWeek the minimal number of days in the first
       
  1410          *                               week (1..7)
       
  1411          * @return this {@code Calendar.Builder}
       
  1412          * @throws IllegalArgumentException if {@code firstDayOfWeek} or
       
  1413          *                                  {@code minimalDaysInFirstWeek} is invalid
       
  1414          * @see Calendar#getFirstDayOfWeek()
       
  1415          * @see Calendar#getMinimalDaysInFirstWeek()
       
  1416          */
       
  1417         public Builder setWeekDefinition(int firstDayOfWeek, int minimalDaysInFirstWeek) {
       
  1418             if (!isValidWeekParameter(firstDayOfWeek)
       
  1419                     || !isValidWeekParameter(minimalDaysInFirstWeek)) {
       
  1420                 throw new IllegalArgumentException();
       
  1421             }
       
  1422             this.firstDayOfWeek = firstDayOfWeek;
       
  1423             this.minimalDaysInFirstWeek = minimalDaysInFirstWeek;
       
  1424             return this;
       
  1425         }
       
  1426 
       
  1427         /**
       
  1428          * Returns a {@code Calendar} built from the parameters set by the
       
  1429          * setter methods. The calendar type given by the {@link #setCalendarType(String)
       
  1430          * setCalendarType} method or the {@linkplain #setLocale(Locale) locale} is
       
  1431          * used to determine what {@code Calendar} to be created. If no explicit
       
  1432          * calendar type is given, the locale's default calendar is created.
       
  1433          *
       
  1434          * <p>If the calendar type is {@code "iso8601"}, the
       
  1435          * {@linkplain GregorianCalendar#setGregorianChange(Date) Gregorian change date}
       
  1436          * of a {@link GregorianCalendar} is set to {@code Date(Long.MIN_VALUE)}
       
  1437          * to be the <em>proleptic</em> Gregorian calendar. Its week definition
       
  1438          * parameters are also set to be <a
       
  1439          * href="GregorianCalendar.html#iso8601_compatible_setting">compatible
       
  1440          * with the ISO 8601 standard</a>. Note that the
       
  1441          * {@link GregorianCalendar#getCalendarType() getCalendarType} method of
       
  1442          * a {@code GregorianCalendar} created with {@code "iso8601"} returns
       
  1443          * {@code "gregory"}.
       
  1444          *
       
  1445          * <p>The default values are used for locale and time zone if these
       
  1446          * parameters haven't been given explicitly.
       
  1447          *
       
  1448          * <p>Any out of range field values are either normalized in lenient
       
  1449          * mode or detected as an invalid value in non-lenient mode.
       
  1450          *
       
  1451          * @return a {@code Calendar} built with parameters of this {@code
       
  1452          *         Calendar.Builder}
       
  1453          * @throws IllegalArgumentException if the calendar type is unknown, or
       
  1454          *             if any invalid field values are given in non-lenient mode, or
       
  1455          *             if a week date is given for the calendar type that doesn't
       
  1456          *             support week dates.
       
  1457          * @see Calendar#getInstance(TimeZone, Locale)
       
  1458          * @see Locale#getDefault(Locale.Category)
       
  1459          * @see TimeZone#getDefault()
       
  1460          */
       
  1461         public Calendar build() {
       
  1462             if (locale == null) {
       
  1463                 locale = Locale.getDefault();
       
  1464             }
       
  1465             if (zone == null) {
       
  1466                 zone = TimeZone.getDefault();
       
  1467             }
       
  1468             Calendar cal;
       
  1469             if (type == null) {
       
  1470                 type = locale.getUnicodeLocaleType("ca");
       
  1471             }
       
  1472             if (type == null) {
       
  1473                 if (locale.getCountry() == "TH"
       
  1474                     && locale.getLanguage() == "th") {
       
  1475                     type = "buddhist";
       
  1476                 } else {
       
  1477                     type = "gregory";
       
  1478                 }
       
  1479             }
       
  1480             switch (type) {
       
  1481             case "gregory":
       
  1482                 cal = new GregorianCalendar(zone, locale, true);
       
  1483                 break;
       
  1484             case "iso8601":
       
  1485                 GregorianCalendar gcal = new GregorianCalendar(zone, locale, true);
       
  1486                 // make gcal a proleptic Gregorian
       
  1487                 gcal.setGregorianChange(new Date(Long.MIN_VALUE));
       
  1488                 // and week definition to be compatible with ISO 8601
       
  1489                 setWeekDefinition(MONDAY, 4);
       
  1490                 cal = gcal;
       
  1491                 break;
       
  1492             case "buddhist":
       
  1493                 cal = new BuddhistCalendar(zone, locale);
       
  1494                 cal.clear();
       
  1495                 break;
       
  1496             case "japanese":
       
  1497                 cal = new JapaneseImperialCalendar(zone, locale, true);
       
  1498                 break;
       
  1499             default:
       
  1500                 throw new IllegalArgumentException("unknown calendar type: " + type);
       
  1501             }
       
  1502             cal.setLenient(lenient);
       
  1503             if (firstDayOfWeek != 0) {
       
  1504                 cal.setFirstDayOfWeek(firstDayOfWeek);
       
  1505                 cal.setMinimalDaysInFirstWeek(minimalDaysInFirstWeek);
       
  1506             }
       
  1507             if (isInstantSet()) {
       
  1508                 cal.setTimeInMillis(instant);
       
  1509                 cal.complete();
       
  1510                 return cal;
       
  1511             }
       
  1512 
       
  1513             if (fields != null) {
       
  1514                 boolean weekDate = isSet(WEEK_YEAR)
       
  1515                                        && fields[WEEK_YEAR] > fields[YEAR];
       
  1516                 if (weekDate && !cal.isWeekDateSupported()) {
       
  1517                     throw new IllegalArgumentException("week date is unsupported by " + type);
       
  1518                 }
       
  1519 
       
  1520                 // Set the fields from the min stamp to the max stamp so that
       
  1521                 // the fields resolution works in the Calendar.
       
  1522                 for (int stamp = MINIMUM_USER_STAMP; stamp < nextStamp; stamp++) {
       
  1523                     for (int index = 0; index <= maxFieldIndex; index++) {
       
  1524                         if (fields[index] == stamp) {
       
  1525                             cal.set(index, fields[NFIELDS + index]);
       
  1526                             break;
       
  1527                         }
       
  1528                     }
       
  1529                 }
       
  1530 
       
  1531                 if (weekDate) {
       
  1532                     int weekOfYear = isSet(WEEK_OF_YEAR) ? fields[NFIELDS + WEEK_OF_YEAR] : 1;
       
  1533                     int dayOfWeek = isSet(DAY_OF_WEEK)
       
  1534                                     ? fields[NFIELDS + DAY_OF_WEEK] : cal.getFirstDayOfWeek();
       
  1535                     cal.setWeekDate(fields[NFIELDS + WEEK_YEAR], weekOfYear, dayOfWeek);
       
  1536                 }
       
  1537                 cal.complete();
       
  1538             }
       
  1539 
       
  1540             return cal;
       
  1541         }
       
  1542 
       
  1543         private void allocateFields() {
       
  1544             if (fields == null) {
       
  1545                 fields = new int[NFIELDS * 2];
       
  1546                 nextStamp = MINIMUM_USER_STAMP;
       
  1547                 maxFieldIndex = -1;
       
  1548             }
       
  1549         }
       
  1550 
       
  1551         private void internalSet(int field, int value) {
       
  1552             fields[field] = nextStamp++;
       
  1553             if (nextStamp < 0) {
       
  1554                 throw new IllegalStateException("stamp counter overflow");
       
  1555             }
       
  1556             fields[NFIELDS + field] = value;
       
  1557             if (field > maxFieldIndex && field < WEEK_YEAR) {
       
  1558                 maxFieldIndex = field;
       
  1559             }
       
  1560         }
       
  1561 
       
  1562         private boolean isInstantSet() {
       
  1563             return nextStamp == COMPUTED;
       
  1564         }
       
  1565 
       
  1566         private boolean isSet(int index) {
       
  1567             return fields != null && fields[index] > UNSET;
       
  1568         }
       
  1569 
       
  1570         private boolean isValidWeekParameter(int value) {
       
  1571             return value > 0 && value <= 7;
       
  1572         }
       
  1573     }
       
  1574 
       
  1575     /**
       
  1576      * Constructs a Calendar with the default time zone
       
  1577      * and the default {@link java.util.Locale.Category#FORMAT FORMAT}
       
  1578      * locale.
       
  1579      * @see     TimeZone#getDefault
       
  1580      */
       
  1581     protected Calendar()
       
  1582     {
       
  1583         this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
       
  1584         sharedZone = true;
       
  1585     }
       
  1586 
       
  1587     /**
       
  1588      * Constructs a calendar with the specified time zone and locale.
       
  1589      *
       
  1590      * @param zone the time zone to use
       
  1591      * @param aLocale the locale for the week data
       
  1592      */
       
  1593     protected Calendar(TimeZone zone, Locale aLocale)
       
  1594     {
       
  1595         fields = new int[FIELD_COUNT];
       
  1596         isSet = new boolean[FIELD_COUNT];
       
  1597         stamp = new int[FIELD_COUNT];
       
  1598 
       
  1599         this.zone = zone;
       
  1600         setWeekCountData(aLocale);
       
  1601     }
       
  1602 
       
  1603     /**
       
  1604      * Gets a calendar using the default time zone and locale. The
       
  1605      * <code>Calendar</code> returned is based on the current time
       
  1606      * in the default time zone with the default
       
  1607      * {@link Locale.Category#FORMAT FORMAT} locale.
       
  1608      *
       
  1609      * @return a Calendar.
       
  1610      */
       
  1611     public static Calendar getInstance()
       
  1612     {
       
  1613         return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT));
       
  1614     }
       
  1615 
       
  1616     /**
       
  1617      * Gets a calendar using the specified time zone and default locale.
       
  1618      * The <code>Calendar</code> returned is based on the current time
       
  1619      * in the given time zone with the default
       
  1620      * {@link Locale.Category#FORMAT FORMAT} locale.
       
  1621      *
       
  1622      * @param zone the time zone to use
       
  1623      * @return a Calendar.
       
  1624      */
       
  1625     public static Calendar getInstance(TimeZone zone)
       
  1626     {
       
  1627         return createCalendar(zone, Locale.getDefault(Locale.Category.FORMAT));
       
  1628     }
       
  1629 
       
  1630     /**
       
  1631      * Gets a calendar using the default time zone and specified locale.
       
  1632      * The <code>Calendar</code> returned is based on the current time
       
  1633      * in the default time zone with the given locale.
       
  1634      *
       
  1635      * @param aLocale the locale for the week data
       
  1636      * @return a Calendar.
       
  1637      */
       
  1638     public static Calendar getInstance(Locale aLocale)
       
  1639     {
       
  1640         return createCalendar(TimeZone.getDefault(), aLocale);
       
  1641     }
       
  1642 
       
  1643     /**
       
  1644      * Gets a calendar with the specified time zone and locale.
       
  1645      * The <code>Calendar</code> returned is based on the current time
       
  1646      * in the given time zone with the given locale.
       
  1647      *
       
  1648      * @param zone the time zone to use
       
  1649      * @param aLocale the locale for the week data
       
  1650      * @return a Calendar.
       
  1651      */
       
  1652     public static Calendar getInstance(TimeZone zone,
       
  1653                                        Locale aLocale)
       
  1654     {
       
  1655         return createCalendar(zone, aLocale);
       
  1656     }
       
  1657 
       
  1658     private static Calendar createCalendar(TimeZone zone,
       
  1659                                            Locale aLocale)
       
  1660     {
       
  1661         CalendarProvider provider =
       
  1662             LocaleProviderAdapter.getAdapter(CalendarProvider.class, aLocale)
       
  1663                                  .getCalendarProvider();
       
  1664         if (provider != null) {
       
  1665             try {
       
  1666                 return provider.getInstance(zone, aLocale);
       
  1667             } catch (IllegalArgumentException iae) {
       
  1668                 // fall back to the default instantiation
       
  1669             }
       
  1670         }
       
  1671 
       
  1672         Calendar cal = null;
       
  1673 
       
  1674         if (aLocale.hasExtensions()) {
       
  1675             String caltype = aLocale.getUnicodeLocaleType("ca");
       
  1676             if (caltype != null) {
       
  1677                 switch (caltype) {
       
  1678                 case "buddhist":
       
  1679                 cal = new BuddhistCalendar(zone, aLocale);
       
  1680                     break;
       
  1681                 case "japanese":
       
  1682                     cal = new JapaneseImperialCalendar(zone, aLocale);
       
  1683                     break;
       
  1684                 case "gregory":
       
  1685                     cal = new GregorianCalendar(zone, aLocale);
       
  1686                     break;
       
  1687                 }
       
  1688             }
       
  1689         }
       
  1690         if (cal == null) {
       
  1691             // If no known calendar type is explicitly specified,
       
  1692             // perform the traditional way to create a Calendar:
       
  1693             // create a BuddhistCalendar for th_TH locale,
       
  1694             // a JapaneseImperialCalendar for ja_JP_JP locale, or
       
  1695             // a GregorianCalendar for any other locales.
       
  1696             // NOTE: The language, country and variant strings are interned.
       
  1697             if (aLocale.getLanguage() == "th" && aLocale.getCountry() == "TH") {
       
  1698                 cal = new BuddhistCalendar(zone, aLocale);
       
  1699             } else if (aLocale.getVariant() == "JP" && aLocale.getLanguage() == "ja"
       
  1700                        && aLocale.getCountry() == "JP") {
       
  1701                 cal = new JapaneseImperialCalendar(zone, aLocale);
       
  1702             } else {
       
  1703                 cal = new GregorianCalendar(zone, aLocale);
       
  1704             }
       
  1705         }
       
  1706         return cal;
       
  1707     }
       
  1708 
       
  1709     /**
       
  1710      * Returns an array of all locales for which the <code>getInstance</code>
       
  1711      * methods of this class can return localized instances.
       
  1712      * The array returned must contain at least a <code>Locale</code>
       
  1713      * instance equal to {@link java.util.Locale#US Locale.US}.
       
  1714      *
       
  1715      * @return An array of locales for which localized
       
  1716      *         <code>Calendar</code> instances are available.
       
  1717      */
       
  1718     public static synchronized Locale[] getAvailableLocales()
       
  1719     {
       
  1720         return DateFormat.getAvailableLocales();
       
  1721     }
       
  1722 
       
  1723     /**
       
  1724      * Converts the current calendar field values in {@link #fields fields[]}
       
  1725      * to the millisecond time value
       
  1726      * {@link #time}.
       
  1727      *
       
  1728      * @see #complete()
       
  1729      * @see #computeFields()
       
  1730      */
       
  1731     protected abstract void computeTime();
       
  1732 
       
  1733     /**
       
  1734      * Converts the current millisecond time value {@link #time}
       
  1735      * to calendar field values in {@link #fields fields[]}.
       
  1736      * This allows you to sync up the calendar field values with
       
  1737      * a new time that is set for the calendar.  The time is <em>not</em>
       
  1738      * recomputed first; to recompute the time, then the fields, call the
       
  1739      * {@link #complete()} method.
       
  1740      *
       
  1741      * @see #computeTime()
       
  1742      */
       
  1743     protected abstract void computeFields();
       
  1744 
       
  1745     /**
       
  1746      * Returns a <code>Date</code> object representing this
       
  1747      * <code>Calendar</code>'s time value (millisecond offset from the <a
       
  1748      * href="#Epoch">Epoch</a>").
       
  1749      *
       
  1750      * @return a <code>Date</code> representing the time value.
       
  1751      * @see #setTime(Date)
       
  1752      * @see #getTimeInMillis()
       
  1753      */
       
  1754     public final Date getTime() {
       
  1755         return new Date(getTimeInMillis());
       
  1756     }
       
  1757 
       
  1758     /**
       
  1759      * Sets this Calendar's time with the given <code>Date</code>.
       
  1760      * <p>
       
  1761      * Note: Calling <code>setTime()</code> with
       
  1762      * <code>Date(Long.MAX_VALUE)</code> or <code>Date(Long.MIN_VALUE)</code>
       
  1763      * may yield incorrect field values from <code>get()</code>.
       
  1764      *
       
  1765      * @param date the given Date.
       
  1766      * @see #getTime()
       
  1767      * @see #setTimeInMillis(long)
       
  1768      */
       
  1769     public final void setTime(Date date) {
       
  1770         setTimeInMillis(date.getTime());
       
  1771     }
       
  1772 
       
  1773     /**
       
  1774      * Returns this Calendar's time value in milliseconds.
       
  1775      *
       
  1776      * @return the current time as UTC milliseconds from the epoch.
       
  1777      * @see #getTime()
       
  1778      * @see #setTimeInMillis(long)
       
  1779      */
       
  1780     public long getTimeInMillis() {
       
  1781         if (!isTimeSet) {
       
  1782             updateTime();
       
  1783         }
       
  1784         return time;
       
  1785     }
       
  1786 
       
  1787     /**
       
  1788      * Sets this Calendar's current time from the given long value.
       
  1789      *
       
  1790      * @param millis the new time in UTC milliseconds from the epoch.
       
  1791      * @see #setTime(Date)
       
  1792      * @see #getTimeInMillis()
       
  1793      */
       
  1794     public void setTimeInMillis(long millis) {
       
  1795         // If we don't need to recalculate the calendar field values,
       
  1796         // do nothing.
       
  1797         if (time == millis && isTimeSet && areFieldsSet && areAllFieldsSet
       
  1798             && (zone instanceof ZoneInfo) && !((ZoneInfo)zone).isDirty()) {
       
  1799             return;
       
  1800         }
       
  1801         time = millis;
       
  1802         isTimeSet = true;
       
  1803         areFieldsSet = false;
       
  1804         computeFields();
       
  1805         areAllFieldsSet = areFieldsSet = true;
       
  1806     }
       
  1807 
       
  1808     /**
       
  1809      * Returns the value of the given calendar field. In lenient mode,
       
  1810      * all calendar fields are normalized. In non-lenient mode, all
       
  1811      * calendar fields are validated and this method throws an
       
  1812      * exception if any calendar fields have out-of-range values. The
       
  1813      * normalization and validation are handled by the
       
  1814      * {@link #complete()} method, which process is calendar
       
  1815      * system dependent.
       
  1816      *
       
  1817      * @param field the given calendar field.
       
  1818      * @return the value for the given calendar field.
       
  1819      * @throws ArrayIndexOutOfBoundsException if the specified field is out of range
       
  1820      *             (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
       
  1821      * @see #set(int,int)
       
  1822      * @see #complete()
       
  1823      */
       
  1824     public int get(int field)
       
  1825     {
       
  1826         complete();
       
  1827         return internalGet(field);
       
  1828     }
       
  1829 
       
  1830     /**
       
  1831      * Returns the value of the given calendar field. This method does
       
  1832      * not involve normalization or validation of the field value.
       
  1833      *
       
  1834      * @param field the given calendar field.
       
  1835      * @return the value for the given calendar field.
       
  1836      * @see #get(int)
       
  1837      */
       
  1838     protected final int internalGet(int field)
       
  1839     {
       
  1840         return fields[field];
       
  1841     }
       
  1842 
       
  1843     /**
       
  1844      * Sets the value of the given calendar field. This method does
       
  1845      * not affect any setting state of the field in this
       
  1846      * <code>Calendar</code> instance.
       
  1847      *
       
  1848      * @throws IndexOutOfBoundsException if the specified field is out of range
       
  1849      *             (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
       
  1850      * @see #areFieldsSet
       
  1851      * @see #isTimeSet
       
  1852      * @see #areAllFieldsSet
       
  1853      * @see #set(int,int)
       
  1854      */
       
  1855     final void internalSet(int field, int value)
       
  1856     {
       
  1857         fields[field] = value;
       
  1858     }
       
  1859 
       
  1860     /**
       
  1861      * Sets the given calendar field to the given value. The value is not
       
  1862      * interpreted by this method regardless of the leniency mode.
       
  1863      *
       
  1864      * @param field the given calendar field.
       
  1865      * @param value the value to be set for the given calendar field.
       
  1866      * @throws ArrayIndexOutOfBoundsException if the specified field is out of range
       
  1867      *             (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
       
  1868      * in non-lenient mode.
       
  1869      * @see #set(int,int,int)
       
  1870      * @see #set(int,int,int,int,int)
       
  1871      * @see #set(int,int,int,int,int,int)
       
  1872      * @see #get(int)
       
  1873      */
       
  1874     public void set(int field, int value)
       
  1875     {
       
  1876         // If the fields are partially normalized, calculate all the
       
  1877         // fields before changing any fields.
       
  1878         if (areFieldsSet && !areAllFieldsSet) {
       
  1879             computeFields();
       
  1880         }
       
  1881         internalSet(field, value);
       
  1882         isTimeSet = false;
       
  1883         areFieldsSet = false;
       
  1884         isSet[field] = true;
       
  1885         stamp[field] = nextStamp++;
       
  1886         if (nextStamp == Integer.MAX_VALUE) {
       
  1887             adjustStamp();
       
  1888         }
       
  1889     }
       
  1890 
       
  1891     /**
       
  1892      * Sets the values for the calendar fields <code>YEAR</code>,
       
  1893      * <code>MONTH</code>, and <code>DAY_OF_MONTH</code>.
       
  1894      * Previous values of other calendar fields are retained.  If this is not desired,
       
  1895      * call {@link #clear()} first.
       
  1896      *
       
  1897      * @param year the value used to set the <code>YEAR</code> calendar field.
       
  1898      * @param month the value used to set the <code>MONTH</code> calendar field.
       
  1899      * Month value is 0-based. e.g., 0 for January.
       
  1900      * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
       
  1901      * @see #set(int,int)
       
  1902      * @see #set(int,int,int,int,int)
       
  1903      * @see #set(int,int,int,int,int,int)
       
  1904      */
       
  1905     public final void set(int year, int month, int date)
       
  1906     {
       
  1907         set(YEAR, year);
       
  1908         set(MONTH, month);
       
  1909         set(DATE, date);
       
  1910     }
       
  1911 
       
  1912     /**
       
  1913      * Sets the values for the calendar fields <code>YEAR</code>,
       
  1914      * <code>MONTH</code>, <code>DAY_OF_MONTH</code>,
       
  1915      * <code>HOUR_OF_DAY</code>, and <code>MINUTE</code>.
       
  1916      * Previous values of other fields are retained.  If this is not desired,
       
  1917      * call {@link #clear()} first.
       
  1918      *
       
  1919      * @param year the value used to set the <code>YEAR</code> calendar field.
       
  1920      * @param month the value used to set the <code>MONTH</code> calendar field.
       
  1921      * Month value is 0-based. e.g., 0 for January.
       
  1922      * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
       
  1923      * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field.
       
  1924      * @param minute the value used to set the <code>MINUTE</code> calendar field.
       
  1925      * @see #set(int,int)
       
  1926      * @see #set(int,int,int)
       
  1927      * @see #set(int,int,int,int,int,int)
       
  1928      */
       
  1929     public final void set(int year, int month, int date, int hourOfDay, int minute)
       
  1930     {
       
  1931         set(YEAR, year);
       
  1932         set(MONTH, month);
       
  1933         set(DATE, date);
       
  1934         set(HOUR_OF_DAY, hourOfDay);
       
  1935         set(MINUTE, minute);
       
  1936     }
       
  1937 
       
  1938     /**
       
  1939      * Sets the values for the fields <code>YEAR</code>, <code>MONTH</code>,
       
  1940      * <code>DAY_OF_MONTH</code>, <code>HOUR_OF_DAY</code>, <code>MINUTE</code>, and
       
  1941      * <code>SECOND</code>.
       
  1942      * Previous values of other fields are retained.  If this is not desired,
       
  1943      * call {@link #clear()} first.
       
  1944      *
       
  1945      * @param year the value used to set the <code>YEAR</code> calendar field.
       
  1946      * @param month the value used to set the <code>MONTH</code> calendar field.
       
  1947      * Month value is 0-based. e.g., 0 for January.
       
  1948      * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
       
  1949      * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field.
       
  1950      * @param minute the value used to set the <code>MINUTE</code> calendar field.
       
  1951      * @param second the value used to set the <code>SECOND</code> calendar field.
       
  1952      * @see #set(int,int)
       
  1953      * @see #set(int,int,int)
       
  1954      * @see #set(int,int,int,int,int)
       
  1955      */
       
  1956     public final void set(int year, int month, int date, int hourOfDay, int minute,
       
  1957                           int second)
       
  1958     {
       
  1959         set(YEAR, year);
       
  1960         set(MONTH, month);
       
  1961         set(DATE, date);
       
  1962         set(HOUR_OF_DAY, hourOfDay);
       
  1963         set(MINUTE, minute);
       
  1964         set(SECOND, second);
       
  1965     }
       
  1966 
       
  1967     /**
       
  1968      * Sets all the calendar field values and the time value
       
  1969      * (millisecond offset from the <a href="#Epoch">Epoch</a>) of
       
  1970      * this <code>Calendar</code> undefined. This means that {@link
       
  1971      * #isSet(int) isSet()} will return <code>false</code> for all the
       
  1972      * calendar fields, and the date and time calculations will treat
       
  1973      * the fields as if they had never been set. A
       
  1974      * <code>Calendar</code> implementation class may use its specific
       
  1975      * default field values for date/time calculations. For example,
       
  1976      * <code>GregorianCalendar</code> uses 1970 if the
       
  1977      * <code>YEAR</code> field value is undefined.
       
  1978      *
       
  1979      * @see #clear(int)
       
  1980      */
       
  1981     public final void clear()
       
  1982     {
       
  1983         for (int i = 0; i < fields.length; ) {
       
  1984             stamp[i] = fields[i] = 0; // UNSET == 0
       
  1985             isSet[i++] = false;
       
  1986         }
       
  1987         areAllFieldsSet = areFieldsSet = false;
       
  1988         isTimeSet = false;
       
  1989     }
       
  1990 
       
  1991     /**
       
  1992      * Sets the given calendar field value and the time value
       
  1993      * (millisecond offset from the <a href="#Epoch">Epoch</a>) of
       
  1994      * this <code>Calendar</code> undefined. This means that {@link
       
  1995      * #isSet(int) isSet(field)} will return <code>false</code>, and
       
  1996      * the date and time calculations will treat the field as if it
       
  1997      * had never been set. A <code>Calendar</code> implementation
       
  1998      * class may use the field's specific default value for date and
       
  1999      * time calculations.
       
  2000      *
       
  2001      * <p>The {@link #HOUR_OF_DAY}, {@link #HOUR} and {@link #AM_PM}
       
  2002      * fields are handled independently and the <a
       
  2003      * href="#time_resolution">the resolution rule for the time of
       
  2004      * day</a> is applied. Clearing one of the fields doesn't reset
       
  2005      * the hour of day value of this <code>Calendar</code>. Use {@link
       
  2006      * #set(int,int) set(Calendar.HOUR_OF_DAY, 0)} to reset the hour
       
  2007      * value.
       
  2008      *
       
  2009      * @param field the calendar field to be cleared.
       
  2010      * @see #clear()
       
  2011      */
       
  2012     public final void clear(int field)
       
  2013     {
       
  2014         fields[field] = 0;
       
  2015         stamp[field] = UNSET;
       
  2016         isSet[field] = false;
       
  2017 
       
  2018         areAllFieldsSet = areFieldsSet = false;
       
  2019         isTimeSet = false;
       
  2020     }
       
  2021 
       
  2022     /**
       
  2023      * Determines if the given calendar field has a value set,
       
  2024      * including cases that the value has been set by internal fields
       
  2025      * calculations triggered by a <code>get</code> method call.
       
  2026      *
       
  2027      * @param field the calendar field to test
       
  2028      * @return <code>true</code> if the given calendar field has a value set;
       
  2029      * <code>false</code> otherwise.
       
  2030      */
       
  2031     public final boolean isSet(int field)
       
  2032     {
       
  2033         return stamp[field] != UNSET;
       
  2034     }
       
  2035 
       
  2036     /**
       
  2037      * Returns the string representation of the calendar
       
  2038      * <code>field</code> value in the given <code>style</code> and
       
  2039      * <code>locale</code>.  If no string representation is
       
  2040      * applicable, <code>null</code> is returned. This method calls
       
  2041      * {@link Calendar#get(int) get(field)} to get the calendar
       
  2042      * <code>field</code> value if the string representation is
       
  2043      * applicable to the given calendar <code>field</code>.
       
  2044      *
       
  2045      * <p>For example, if this <code>Calendar</code> is a
       
  2046      * <code>GregorianCalendar</code> and its date is 2005-01-01, then
       
  2047      * the string representation of the {@link #MONTH} field would be
       
  2048      * "January" in the long style in an English locale or "Jan" in
       
  2049      * the short style. However, no string representation would be
       
  2050      * available for the {@link #DAY_OF_MONTH} field, and this method
       
  2051      * would return <code>null</code>.
       
  2052      *
       
  2053      * <p>The default implementation supports the calendar fields for
       
  2054      * which a {@link DateFormatSymbols} has names in the given
       
  2055      * <code>locale</code>.
       
  2056      *
       
  2057      * @param field
       
  2058      *        the calendar field for which the string representation
       
  2059      *        is returned
       
  2060      * @param style
       
  2061      *        the style applied to the string representation; one of {@link
       
  2062      *        #SHORT_FORMAT} ({@link #SHORT}), {@link #SHORT_STANDALONE},
       
  2063      *        {@link #LONG_FORMAT} ({@link #LONG}), {@link #LONG_STANDALONE},
       
  2064      *        {@link #NARROW_FORMAT}, or {@link #NARROW_STANDALONE}.
       
  2065      * @param locale
       
  2066      *        the locale for the string representation
       
  2067      *        (any calendar types specified by {@code locale} are ignored)
       
  2068      * @return the string representation of the given
       
  2069      *        {@code field} in the given {@code style}, or
       
  2070      *        {@code null} if no string representation is
       
  2071      *        applicable.
       
  2072      * @exception IllegalArgumentException
       
  2073      *        if {@code field} or {@code style} is invalid,
       
  2074      *        or if this {@code Calendar} is non-lenient and any
       
  2075      *        of the calendar fields have invalid values
       
  2076      * @exception NullPointerException
       
  2077      *        if {@code locale} is null
       
  2078      * @since 1.6
       
  2079      */
       
  2080     public String getDisplayName(int field, int style, Locale locale) {
       
  2081         if (!checkDisplayNameParams(field, style, SHORT, NARROW_FORMAT, locale,
       
  2082                             ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
       
  2083             return null;
       
  2084         }
       
  2085 
       
  2086         // the standalone and narrow styles are supported only through CalendarDataProviders.
       
  2087         if (isStandaloneStyle(style) || isNarrowStyle(style)) {
       
  2088             return CalendarDataUtility.retrieveFieldValueName(getCalendarType(),
       
  2089                                                               field, get(field),
       
  2090                                                               style, locale);
       
  2091         }
       
  2092 
       
  2093         DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
       
  2094         String[] strings = getFieldStrings(field, style, symbols);
       
  2095         if (strings != null) {
       
  2096             int fieldValue = get(field);
       
  2097             if (fieldValue < strings.length) {
       
  2098                 return strings[fieldValue];
       
  2099             }
       
  2100         }
       
  2101         return null;
       
  2102     }
       
  2103 
       
  2104     /**
       
  2105      * Returns a {@code Map} containing all names of the calendar
       
  2106      * {@code field} in the given {@code style} and
       
  2107      * {@code locale} and their corresponding field values. For
       
  2108      * example, if this {@code Calendar} is a {@link
       
  2109      * GregorianCalendar}, the returned map would contain "Jan" to
       
  2110      * {@link #JANUARY}, "Feb" to {@link #FEBRUARY}, and so on, in the
       
  2111      * {@linkplain #SHORT short} style in an English locale.
       
  2112      *
       
  2113      * <p>Narrow names may not be unique due to use of single characters,
       
  2114      * such as "S" for Sunday and Saturday. In that case narrow names are not
       
  2115      * included in the returned {@code Map}.
       
  2116      *
       
  2117      * <p>The values of other calendar fields may be taken into
       
  2118      * account to determine a set of display names. For example, if
       
  2119      * this {@code Calendar} is a lunisolar calendar system and
       
  2120      * the year value given by the {@link #YEAR} field has a leap
       
  2121      * month, this method would return month names containing the leap
       
  2122      * month name, and month names are mapped to their values specific
       
  2123      * for the year.
       
  2124      *
       
  2125      * <p>The default implementation supports display names contained in
       
  2126      * a {@link DateFormatSymbols}. For example, if {@code field}
       
  2127      * is {@link #MONTH} and {@code style} is {@link
       
  2128      * #ALL_STYLES}, this method returns a {@code Map} containing
       
  2129      * all strings returned by {@link DateFormatSymbols#getShortMonths()}
       
  2130      * and {@link DateFormatSymbols#getMonths()}.
       
  2131      *
       
  2132      * @param field
       
  2133      *        the calendar field for which the display names are returned
       
  2134      * @param style
       
  2135      *        the style applied to the string representation; one of {@link
       
  2136      *        #SHORT_FORMAT} ({@link #SHORT}), {@link #SHORT_STANDALONE},
       
  2137      *        {@link #LONG_FORMAT} ({@link #LONG}), {@link #LONG_STANDALONE},
       
  2138      *        {@link #NARROW_FORMAT}, or {@link #NARROW_STANDALONE}
       
  2139      * @param locale
       
  2140      *        the locale for the display names
       
  2141      * @return a {@code Map} containing all display names in
       
  2142      *        {@code style} and {@code locale} and their
       
  2143      *        field values, or {@code null} if no display names
       
  2144      *        are defined for {@code field}
       
  2145      * @exception IllegalArgumentException
       
  2146      *        if {@code field} or {@code style} is invalid,
       
  2147      *        or if this {@code Calendar} is non-lenient and any
       
  2148      *        of the calendar fields have invalid values
       
  2149      * @exception NullPointerException
       
  2150      *        if {@code locale} is null
       
  2151      * @since 1.6
       
  2152      */
       
  2153     public Map<String, Integer> getDisplayNames(int field, int style, Locale locale) {
       
  2154         if (!checkDisplayNameParams(field, style, ALL_STYLES, NARROW_FORMAT, locale,
       
  2155                                     ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
       
  2156             return null;
       
  2157         }
       
  2158         if (style == ALL_STYLES || isStandaloneStyle(style)) {
       
  2159             return CalendarDataUtility.retrieveFieldValueNames(getCalendarType(), field, style, locale);
       
  2160         }
       
  2161         // SHORT, LONG, or NARROW
       
  2162         return getDisplayNamesImpl(field, style, locale);
       
  2163     }
       
  2164 
       
  2165     private Map<String,Integer> getDisplayNamesImpl(int field, int style, Locale locale) {
       
  2166         DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
       
  2167         String[] strings = getFieldStrings(field, style, symbols);
       
  2168         if (strings != null) {
       
  2169             Map<String,Integer> names = new HashMap<>();
       
  2170             for (int i = 0; i < strings.length; i++) {
       
  2171                 if (strings[i].length() == 0) {
       
  2172                     continue;
       
  2173                 }
       
  2174                 names.put(strings[i], i);
       
  2175             }
       
  2176             return names;
       
  2177         }
       
  2178         return null;
       
  2179     }
       
  2180 
       
  2181     boolean checkDisplayNameParams(int field, int style, int minStyle, int maxStyle,
       
  2182                                    Locale locale, int fieldMask) {
       
  2183         int baseStyle = getBaseStyle(style); // Ignore the standalone mask
       
  2184         if (field < 0 || field >= fields.length ||
       
  2185             baseStyle < minStyle || baseStyle > maxStyle) {
       
  2186             throw new IllegalArgumentException();
       
  2187         }
       
  2188         if (locale == null) {
       
  2189             throw new NullPointerException();
       
  2190         }
       
  2191         return isFieldSet(fieldMask, field);
       
  2192     }
       
  2193 
       
  2194     private String[] getFieldStrings(int field, int style, DateFormatSymbols symbols) {
       
  2195         int baseStyle = getBaseStyle(style); // ignore the standalone mask
       
  2196 
       
  2197         // DateFormatSymbols doesn't support any narrow names.
       
  2198         if (baseStyle == NARROW_FORMAT) {
       
  2199             return null;
       
  2200         }
       
  2201 
       
  2202         String[] strings = null;
       
  2203         switch (field) {
       
  2204         case ERA:
       
  2205             strings = symbols.getEras();
       
  2206             break;
       
  2207 
       
  2208         case MONTH:
       
  2209             strings = (baseStyle == LONG) ? symbols.getMonths() : symbols.getShortMonths();
       
  2210             break;
       
  2211 
       
  2212         case DAY_OF_WEEK:
       
  2213             strings = (baseStyle == LONG) ? symbols.getWeekdays() : symbols.getShortWeekdays();
       
  2214             break;
       
  2215 
       
  2216         case AM_PM:
       
  2217             strings = symbols.getAmPmStrings();
       
  2218             break;
       
  2219         }
       
  2220         return strings;
       
  2221     }
       
  2222 
       
  2223     /**
       
  2224      * Fills in any unset fields in the calendar fields. First, the {@link
       
  2225      * #computeTime()} method is called if the time value (millisecond offset
       
  2226      * from the <a href="#Epoch">Epoch</a>) has not been calculated from
       
  2227      * calendar field values. Then, the {@link #computeFields()} method is
       
  2228      * called to calculate all calendar field values.
       
  2229      */
       
  2230     protected void complete()
       
  2231     {
       
  2232         if (!isTimeSet) {
       
  2233             updateTime();
       
  2234         }
       
  2235         if (!areFieldsSet || !areAllFieldsSet) {
       
  2236             computeFields(); // fills in unset fields
       
  2237             areAllFieldsSet = areFieldsSet = true;
       
  2238         }
       
  2239     }
       
  2240 
       
  2241     /**
       
  2242      * Returns whether the value of the specified calendar field has been set
       
  2243      * externally by calling one of the setter methods rather than by the
       
  2244      * internal time calculation.
       
  2245      *
       
  2246      * @return <code>true</code> if the field has been set externally,
       
  2247      * <code>false</code> otherwise.
       
  2248      * @exception IndexOutOfBoundsException if the specified
       
  2249      *                <code>field</code> is out of range
       
  2250      *               (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
       
  2251      * @see #selectFields()
       
  2252      * @see #setFieldsComputed(int)
       
  2253      */
       
  2254     final boolean isExternallySet(int field) {
       
  2255         return stamp[field] >= MINIMUM_USER_STAMP;
       
  2256     }
       
  2257 
       
  2258     /**
       
  2259      * Returns a field mask (bit mask) indicating all calendar fields that
       
  2260      * have the state of externally or internally set.
       
  2261      *
       
  2262      * @return a bit mask indicating set state fields
       
  2263      */
       
  2264     final int getSetStateFields() {
       
  2265         int mask = 0;
       
  2266         for (int i = 0; i < fields.length; i++) {
       
  2267             if (stamp[i] != UNSET) {
       
  2268                 mask |= 1 << i;
       
  2269             }
       
  2270         }
       
  2271         return mask;
       
  2272     }
       
  2273 
       
  2274     /**
       
  2275      * Sets the state of the specified calendar fields to
       
  2276      * <em>computed</em>. This state means that the specified calendar fields
       
  2277      * have valid values that have been set by internal time calculation
       
  2278      * rather than by calling one of the setter methods.
       
  2279      *
       
  2280      * @param fieldMask the field to be marked as computed.
       
  2281      * @exception IndexOutOfBoundsException if the specified
       
  2282      *                <code>field</code> is out of range
       
  2283      *               (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
       
  2284      * @see #isExternallySet(int)
       
  2285      * @see #selectFields()
       
  2286      */
       
  2287     final void setFieldsComputed(int fieldMask) {
       
  2288         if (fieldMask == ALL_FIELDS) {
       
  2289             for (int i = 0; i < fields.length; i++) {
       
  2290                 stamp[i] = COMPUTED;
       
  2291                 isSet[i] = true;
       
  2292             }
       
  2293             areFieldsSet = areAllFieldsSet = true;
       
  2294         } else {
       
  2295             for (int i = 0; i < fields.length; i++) {
       
  2296                 if ((fieldMask & 1) == 1) {
       
  2297                     stamp[i] = COMPUTED;
       
  2298                     isSet[i] = true;
       
  2299                 } else {
       
  2300                     if (areAllFieldsSet && !isSet[i]) {
       
  2301                         areAllFieldsSet = false;
       
  2302                     }
       
  2303                 }
       
  2304                 fieldMask >>>= 1;
       
  2305             }
       
  2306         }
       
  2307     }
       
  2308 
       
  2309     /**
       
  2310      * Sets the state of the calendar fields that are <em>not</em> specified
       
  2311      * by <code>fieldMask</code> to <em>unset</em>. If <code>fieldMask</code>
       
  2312      * specifies all the calendar fields, then the state of this
       
  2313      * <code>Calendar</code> becomes that all the calendar fields are in sync
       
  2314      * with the time value (millisecond offset from the Epoch).
       
  2315      *
       
  2316      * @param fieldMask the field mask indicating which calendar fields are in
       
  2317      * sync with the time value.
       
  2318      * @exception IndexOutOfBoundsException if the specified
       
  2319      *                <code>field</code> is out of range
       
  2320      *               (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
       
  2321      * @see #isExternallySet(int)
       
  2322      * @see #selectFields()
       
  2323      */
       
  2324     final void setFieldsNormalized(int fieldMask) {
       
  2325         if (fieldMask != ALL_FIELDS) {
       
  2326             for (int i = 0; i < fields.length; i++) {
       
  2327                 if ((fieldMask & 1) == 0) {
       
  2328                     stamp[i] = fields[i] = 0; // UNSET == 0
       
  2329                     isSet[i] = false;
       
  2330                 }
       
  2331                 fieldMask >>= 1;
       
  2332             }
       
  2333         }
       
  2334 
       
  2335         // Some or all of the fields are in sync with the
       
  2336         // milliseconds, but the stamp values are not normalized yet.
       
  2337         areFieldsSet = true;
       
  2338         areAllFieldsSet = false;
       
  2339     }
       
  2340 
       
  2341     /**
       
  2342      * Returns whether the calendar fields are partially in sync with the time
       
  2343      * value or fully in sync but not stamp values are not normalized yet.
       
  2344      */
       
  2345     final boolean isPartiallyNormalized() {
       
  2346         return areFieldsSet && !areAllFieldsSet;
       
  2347     }
       
  2348 
       
  2349     /**
       
  2350      * Returns whether the calendar fields are fully in sync with the time
       
  2351      * value.
       
  2352      */
       
  2353     final boolean isFullyNormalized() {
       
  2354         return areFieldsSet && areAllFieldsSet;
       
  2355     }
       
  2356 
       
  2357     /**
       
  2358      * Marks this Calendar as not sync'd.
       
  2359      */
       
  2360     final void setUnnormalized() {
       
  2361         areFieldsSet = areAllFieldsSet = false;
       
  2362     }
       
  2363 
       
  2364     /**
       
  2365      * Returns whether the specified <code>field</code> is on in the
       
  2366      * <code>fieldMask</code>.
       
  2367      */
       
  2368     static boolean isFieldSet(int fieldMask, int field) {
       
  2369         return (fieldMask & (1 << field)) != 0;
       
  2370     }
       
  2371 
       
  2372     /**
       
  2373      * Returns a field mask indicating which calendar field values
       
  2374      * to be used to calculate the time value. The calendar fields are
       
  2375      * returned as a bit mask, each bit of which corresponds to a field, i.e.,
       
  2376      * the mask value of <code>field</code> is <code>(1 &lt;&lt;
       
  2377      * field)</code>. For example, 0x26 represents the <code>YEAR</code>,
       
  2378      * <code>MONTH</code>, and <code>DAY_OF_MONTH</code> fields (i.e., 0x26 is
       
  2379      * equal to
       
  2380      * <code>(1&lt;&lt;YEAR)|(1&lt;&lt;MONTH)|(1&lt;&lt;DAY_OF_MONTH))</code>.
       
  2381      *
       
  2382      * <p>This method supports the calendar fields resolution as described in
       
  2383      * the class description. If the bit mask for a given field is on and its
       
  2384      * field has not been set (i.e., <code>isSet(field)</code> is
       
  2385      * <code>false</code>), then the default value of the field has to be
       
  2386      * used, which case means that the field has been selected because the
       
  2387      * selected combination involves the field.
       
  2388      *
       
  2389      * @return a bit mask of selected fields
       
  2390      * @see #isExternallySet(int)
       
  2391      */
       
  2392     final int selectFields() {
       
  2393         // This implementation has been taken from the GregorianCalendar class.
       
  2394 
       
  2395         // The YEAR field must always be used regardless of its SET
       
  2396         // state because YEAR is a mandatory field to determine the date
       
  2397         // and the default value (EPOCH_YEAR) may change through the
       
  2398         // normalization process.
       
  2399         int fieldMask = YEAR_MASK;
       
  2400 
       
  2401         if (stamp[ERA] != UNSET) {
       
  2402             fieldMask |= ERA_MASK;
       
  2403         }
       
  2404         // Find the most recent group of fields specifying the day within
       
  2405         // the year.  These may be any of the following combinations:
       
  2406         //   MONTH + DAY_OF_MONTH
       
  2407         //   MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
       
  2408         //   MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
       
  2409         //   DAY_OF_YEAR
       
  2410         //   WEEK_OF_YEAR + DAY_OF_WEEK
       
  2411         // We look for the most recent of the fields in each group to determine
       
  2412         // the age of the group.  For groups involving a week-related field such
       
  2413         // as WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR, both the
       
  2414         // week-related field and the DAY_OF_WEEK must be set for the group as a
       
  2415         // whole to be considered.  (See bug 4153860 - liu 7/24/98.)
       
  2416         int dowStamp = stamp[DAY_OF_WEEK];
       
  2417         int monthStamp = stamp[MONTH];
       
  2418         int domStamp = stamp[DAY_OF_MONTH];
       
  2419         int womStamp = aggregateStamp(stamp[WEEK_OF_MONTH], dowStamp);
       
  2420         int dowimStamp = aggregateStamp(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
       
  2421         int doyStamp = stamp[DAY_OF_YEAR];
       
  2422         int woyStamp = aggregateStamp(stamp[WEEK_OF_YEAR], dowStamp);
       
  2423 
       
  2424         int bestStamp = domStamp;
       
  2425         if (womStamp > bestStamp) {
       
  2426             bestStamp = womStamp;
       
  2427         }
       
  2428         if (dowimStamp > bestStamp) {
       
  2429             bestStamp = dowimStamp;
       
  2430         }
       
  2431         if (doyStamp > bestStamp) {
       
  2432             bestStamp = doyStamp;
       
  2433         }
       
  2434         if (woyStamp > bestStamp) {
       
  2435             bestStamp = woyStamp;
       
  2436         }
       
  2437 
       
  2438         /* No complete combination exists.  Look for WEEK_OF_MONTH,
       
  2439          * DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR alone.  Treat DAY_OF_WEEK alone
       
  2440          * as DAY_OF_WEEK_IN_MONTH.
       
  2441          */
       
  2442         if (bestStamp == UNSET) {
       
  2443             womStamp = stamp[WEEK_OF_MONTH];
       
  2444             dowimStamp = Math.max(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
       
  2445             woyStamp = stamp[WEEK_OF_YEAR];
       
  2446             bestStamp = Math.max(Math.max(womStamp, dowimStamp), woyStamp);
       
  2447 
       
  2448             /* Treat MONTH alone or no fields at all as DAY_OF_MONTH.  This may
       
  2449              * result in bestStamp = domStamp = UNSET if no fields are set,
       
  2450              * which indicates DAY_OF_MONTH.
       
  2451              */
       
  2452             if (bestStamp == UNSET) {
       
  2453                 bestStamp = domStamp = monthStamp;
       
  2454             }
       
  2455         }
       
  2456 
       
  2457         if (bestStamp == domStamp ||
       
  2458            (bestStamp == womStamp && stamp[WEEK_OF_MONTH] >= stamp[WEEK_OF_YEAR]) ||
       
  2459            (bestStamp == dowimStamp && stamp[DAY_OF_WEEK_IN_MONTH] >= stamp[WEEK_OF_YEAR])) {
       
  2460             fieldMask |= MONTH_MASK;
       
  2461             if (bestStamp == domStamp) {
       
  2462                 fieldMask |= DAY_OF_MONTH_MASK;
       
  2463             } else {
       
  2464                 assert (bestStamp == womStamp || bestStamp == dowimStamp);
       
  2465                 if (dowStamp != UNSET) {
       
  2466                     fieldMask |= DAY_OF_WEEK_MASK;
       
  2467                 }
       
  2468                 if (womStamp == dowimStamp) {
       
  2469                     // When they are equal, give the priority to
       
  2470                     // WEEK_OF_MONTH for compatibility.
       
  2471                     if (stamp[WEEK_OF_MONTH] >= stamp[DAY_OF_WEEK_IN_MONTH]) {
       
  2472                         fieldMask |= WEEK_OF_MONTH_MASK;
       
  2473                     } else {
       
  2474                         fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;
       
  2475                     }
       
  2476                 } else {
       
  2477                     if (bestStamp == womStamp) {
       
  2478                         fieldMask |= WEEK_OF_MONTH_MASK;
       
  2479                     } else {
       
  2480                         assert (bestStamp == dowimStamp);
       
  2481                         if (stamp[DAY_OF_WEEK_IN_MONTH] != UNSET) {
       
  2482                             fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;
       
  2483                         }
       
  2484                     }
       
  2485                 }
       
  2486             }
       
  2487         } else {
       
  2488             assert (bestStamp == doyStamp || bestStamp == woyStamp ||
       
  2489                     bestStamp == UNSET);
       
  2490             if (bestStamp == doyStamp) {
       
  2491                 fieldMask |= DAY_OF_YEAR_MASK;
       
  2492             } else {
       
  2493                 assert (bestStamp == woyStamp);
       
  2494                 if (dowStamp != UNSET) {
       
  2495                     fieldMask |= DAY_OF_WEEK_MASK;
       
  2496                 }
       
  2497                 fieldMask |= WEEK_OF_YEAR_MASK;
       
  2498             }
       
  2499         }
       
  2500 
       
  2501         // Find the best set of fields specifying the time of day.  There
       
  2502         // are only two possibilities here; the HOUR_OF_DAY or the
       
  2503         // AM_PM and the HOUR.
       
  2504         int hourOfDayStamp = stamp[HOUR_OF_DAY];
       
  2505         int hourStamp = aggregateStamp(stamp[HOUR], stamp[AM_PM]);
       
  2506         bestStamp = (hourStamp > hourOfDayStamp) ? hourStamp : hourOfDayStamp;
       
  2507 
       
  2508         // if bestStamp is still UNSET, then take HOUR or AM_PM. (See 4846659)
       
  2509         if (bestStamp == UNSET) {
       
  2510             bestStamp = Math.max(stamp[HOUR], stamp[AM_PM]);
       
  2511         }
       
  2512 
       
  2513         // Hours
       
  2514         if (bestStamp != UNSET) {
       
  2515             if (bestStamp == hourOfDayStamp) {
       
  2516                 fieldMask |= HOUR_OF_DAY_MASK;
       
  2517             } else {
       
  2518                 fieldMask |= HOUR_MASK;
       
  2519                 if (stamp[AM_PM] != UNSET) {
       
  2520                     fieldMask |= AM_PM_MASK;
       
  2521                 }
       
  2522             }
       
  2523         }
       
  2524         if (stamp[MINUTE] != UNSET) {
       
  2525             fieldMask |= MINUTE_MASK;
       
  2526         }
       
  2527         if (stamp[SECOND] != UNSET) {
       
  2528             fieldMask |= SECOND_MASK;
       
  2529         }
       
  2530         if (stamp[MILLISECOND] != UNSET) {
       
  2531             fieldMask |= MILLISECOND_MASK;
       
  2532         }
       
  2533         if (stamp[ZONE_OFFSET] >= MINIMUM_USER_STAMP) {
       
  2534                 fieldMask |= ZONE_OFFSET_MASK;
       
  2535         }
       
  2536         if (stamp[DST_OFFSET] >= MINIMUM_USER_STAMP) {
       
  2537             fieldMask |= DST_OFFSET_MASK;
       
  2538         }
       
  2539 
       
  2540         return fieldMask;
       
  2541     }
       
  2542 
       
  2543     int getBaseStyle(int style) {
       
  2544         return style & ~STANDALONE_MASK;
       
  2545     }
       
  2546 
       
  2547     boolean isStandaloneStyle(int style) {
       
  2548         return (style & STANDALONE_MASK) != 0;
       
  2549     }
       
  2550 
       
  2551     boolean isNarrowStyle(int style) {
       
  2552         return style == NARROW_FORMAT || style == NARROW_STANDALONE;
       
  2553     }
       
  2554 
       
  2555     /**
       
  2556      * Returns the pseudo-time-stamp for two fields, given their
       
  2557      * individual pseudo-time-stamps.  If either of the fields
       
  2558      * is unset, then the aggregate is unset.  Otherwise, the
       
  2559      * aggregate is the later of the two stamps.
       
  2560      */
       
  2561     private static int aggregateStamp(int stamp_a, int stamp_b) {
       
  2562         if (stamp_a == UNSET || stamp_b == UNSET) {
       
  2563             return UNSET;
       
  2564         }
       
  2565         return (stamp_a > stamp_b) ? stamp_a : stamp_b;
       
  2566     }
       
  2567 
       
  2568     /**
       
  2569      * Returns an unmodifiable {@code Set} containing all calendar types
       
  2570      * supported by {@code Calendar} in the runtime environment. The available
       
  2571      * calendar types can be used for the <a
       
  2572      * href="Locale.html#def_locale_extension">Unicode locale extensions</a>.
       
  2573      * The {@code Set} returned contains at least {@code "gregory"}. The
       
  2574      * calendar types don't include aliases, such as {@code "gregorian"} for
       
  2575      * {@code "gregory"}.
       
  2576      *
       
  2577      * @return an unmodifiable {@code Set} containing all available calendar types
       
  2578      * @since 1.8
       
  2579      * @see #getCalendarType()
       
  2580      * @see Calendar.Builder#setCalendarType(String)
       
  2581      * @see Locale#getUnicodeLocaleType(String)
       
  2582      */
       
  2583     public static Set<String> getAvailableCalendarTypes() {
       
  2584         return AvailableCalendarTypes.SET;
       
  2585     }
       
  2586 
       
  2587     private static class AvailableCalendarTypes {
       
  2588         private static final Set<String> SET;
       
  2589         static {
       
  2590             Set<String> set = new HashSet<>(3);
       
  2591             set.add("gregory");
       
  2592             set.add("buddhist");
       
  2593             set.add("japanese");
       
  2594             SET = Collections.unmodifiableSet(set);
       
  2595         }
       
  2596         private AvailableCalendarTypes() {
       
  2597         }
       
  2598     }
       
  2599 
       
  2600     /**
       
  2601      * Returns the calendar type of this {@code Calendar}. Calendar types are
       
  2602      * defined by the <em>Unicode Locale Data Markup Language (LDML)</em>
       
  2603      * specification.
       
  2604      *
       
  2605      * <p>The default implementation of this method returns the class name of
       
  2606      * this {@code Calendar} instance. Any subclasses that implement
       
  2607      * LDML-defined calendar systems should override this method to return
       
  2608      * appropriate calendar types.
       
  2609      *
       
  2610      * @return the LDML-defined calendar type or the class name of this
       
  2611      *         {@code Calendar} instance
       
  2612      * @since 1.8
       
  2613      * @see <a href="Locale.html#def_extensions">Locale extensions</a>
       
  2614      * @see Locale.Builder#setLocale(Locale)
       
  2615      * @see Locale.Builder#setUnicodeLocaleKeyword(String, String)
       
  2616      */
       
  2617     public String getCalendarType() {
       
  2618         return this.getClass().getName();
       
  2619     }
       
  2620 
       
  2621     /**
       
  2622      * Compares this <code>Calendar</code> to the specified
       
  2623      * <code>Object</code>.  The result is <code>true</code> if and only if
       
  2624      * the argument is a <code>Calendar</code> object of the same calendar
       
  2625      * system that represents the same time value (millisecond offset from the
       
  2626      * <a href="#Epoch">Epoch</a>) under the same
       
  2627      * <code>Calendar</code> parameters as this object.
       
  2628      *
       
  2629      * <p>The <code>Calendar</code> parameters are the values represented
       
  2630      * by the <code>isLenient</code>, <code>getFirstDayOfWeek</code>,
       
  2631      * <code>getMinimalDaysInFirstWeek</code> and <code>getTimeZone</code>
       
  2632      * methods. If there is any difference in those parameters
       
  2633      * between the two <code>Calendar</code>s, this method returns
       
  2634      * <code>false</code>.
       
  2635      *
       
  2636      * <p>Use the {@link #compareTo(Calendar) compareTo} method to
       
  2637      * compare only the time values.
       
  2638      *
       
  2639      * @param obj the object to compare with.
       
  2640      * @return <code>true</code> if this object is equal to <code>obj</code>;
       
  2641      * <code>false</code> otherwise.
       
  2642      */
       
  2643     @SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
       
  2644     @Override
       
  2645     public boolean equals(Object obj) {
       
  2646         if (this == obj) {
       
  2647             return true;
       
  2648         }
       
  2649         try {
       
  2650             Calendar that = (Calendar)obj;
       
  2651             return compareTo(getMillisOf(that)) == 0 &&
       
  2652                 lenient == that.lenient &&
       
  2653                 firstDayOfWeek == that.firstDayOfWeek &&
       
  2654                 minimalDaysInFirstWeek == that.minimalDaysInFirstWeek &&
       
  2655                 zone.equals(that.zone);
       
  2656         } catch (Exception e) {
       
  2657             // Note: GregorianCalendar.computeTime throws
       
  2658             // IllegalArgumentException if the ERA value is invalid
       
  2659             // even it's in lenient mode.
       
  2660         }
       
  2661         return false;
       
  2662     }
       
  2663 
       
  2664     /**
       
  2665      * Returns a hash code for this calendar.
       
  2666      *
       
  2667      * @return a hash code value for this object.
       
  2668      * @since 1.2
       
  2669      */
       
  2670     @Override
       
  2671     public int hashCode() {
       
  2672         // 'otheritems' represents the hash code for the previous versions.
       
  2673         int otheritems = (lenient ? 1 : 0)
       
  2674             | (firstDayOfWeek << 1)
       
  2675             | (minimalDaysInFirstWeek << 4)
       
  2676             | (zone.hashCode() << 7);
       
  2677         long t = getMillisOf(this);
       
  2678         return (int) t ^ (int)(t >> 32) ^ otheritems;
       
  2679     }
       
  2680 
       
  2681     /**
       
  2682      * Returns whether this <code>Calendar</code> represents a time
       
  2683      * before the time represented by the specified
       
  2684      * <code>Object</code>. This method is equivalent to:
       
  2685      * <pre>{@code
       
  2686      *         compareTo(when) < 0
       
  2687      * }</pre>
       
  2688      * if and only if <code>when</code> is a <code>Calendar</code>
       
  2689      * instance. Otherwise, the method returns <code>false</code>.
       
  2690      *
       
  2691      * @param when the <code>Object</code> to be compared
       
  2692      * @return <code>true</code> if the time of this
       
  2693      * <code>Calendar</code> is before the time represented by
       
  2694      * <code>when</code>; <code>false</code> otherwise.
       
  2695      * @see     #compareTo(Calendar)
       
  2696      */
       
  2697     public boolean before(Object when) {
       
  2698         return when instanceof Calendar
       
  2699             && compareTo((Calendar)when) < 0;
       
  2700     }
       
  2701 
       
  2702     /**
       
  2703      * Returns whether this <code>Calendar</code> represents a time
       
  2704      * after the time represented by the specified
       
  2705      * <code>Object</code>. This method is equivalent to:
       
  2706      * <pre>{@code
       
  2707      *         compareTo(when) > 0
       
  2708      * }</pre>
       
  2709      * if and only if <code>when</code> is a <code>Calendar</code>
       
  2710      * instance. Otherwise, the method returns <code>false</code>.
       
  2711      *
       
  2712      * @param when the <code>Object</code> to be compared
       
  2713      * @return <code>true</code> if the time of this <code>Calendar</code> is
       
  2714      * after the time represented by <code>when</code>; <code>false</code>
       
  2715      * otherwise.
       
  2716      * @see     #compareTo(Calendar)
       
  2717      */
       
  2718     public boolean after(Object when) {
       
  2719         return when instanceof Calendar
       
  2720             && compareTo((Calendar)when) > 0;
       
  2721     }
       
  2722 
       
  2723     /**
       
  2724      * Compares the time values (millisecond offsets from the <a
       
  2725      * href="#Epoch">Epoch</a>) represented by two
       
  2726      * <code>Calendar</code> objects.
       
  2727      *
       
  2728      * @param anotherCalendar the <code>Calendar</code> to be compared.
       
  2729      * @return the value <code>0</code> if the time represented by the argument
       
  2730      * is equal to the time represented by this <code>Calendar</code>; a value
       
  2731      * less than <code>0</code> if the time of this <code>Calendar</code> is
       
  2732      * before the time represented by the argument; and a value greater than
       
  2733      * <code>0</code> if the time of this <code>Calendar</code> is after the
       
  2734      * time represented by the argument.
       
  2735      * @exception NullPointerException if the specified <code>Calendar</code> is
       
  2736      *            <code>null</code>.
       
  2737      * @exception IllegalArgumentException if the time value of the
       
  2738      * specified <code>Calendar</code> object can't be obtained due to
       
  2739      * any invalid calendar values.
       
  2740      * @since   1.5
       
  2741      */
       
  2742     @Override
       
  2743     public int compareTo(Calendar anotherCalendar) {
       
  2744         return compareTo(getMillisOf(anotherCalendar));
       
  2745     }
       
  2746 
       
  2747     /**
       
  2748      * Adds or subtracts the specified amount of time to the given calendar field,
       
  2749      * based on the calendar's rules. For example, to subtract 5 days from
       
  2750      * the current time of the calendar, you can achieve it by calling:
       
  2751      * <p><code>add(Calendar.DAY_OF_MONTH, -5)</code>.
       
  2752      *
       
  2753      * @param field the calendar field.
       
  2754      * @param amount the amount of date or time to be added to the field.
       
  2755      * @see #roll(int,int)
       
  2756      * @see #set(int,int)
       
  2757      */
       
  2758     abstract public void add(int field, int amount);
       
  2759 
       
  2760     /**
       
  2761      * Adds or subtracts (up/down) a single unit of time on the given time
       
  2762      * field without changing larger fields. For example, to roll the current
       
  2763      * date up by one day, you can achieve it by calling:
       
  2764      * <p>roll(Calendar.DATE, true).
       
  2765      * When rolling on the year or Calendar.YEAR field, it will roll the year
       
  2766      * value in the range between 1 and the value returned by calling
       
  2767      * <code>getMaximum(Calendar.YEAR)</code>.
       
  2768      * When rolling on the month or Calendar.MONTH field, other fields like
       
  2769      * date might conflict and, need to be changed. For instance,
       
  2770      * rolling the month on the date 01/31/96 will result in 02/29/96.
       
  2771      * When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will
       
  2772      * roll the hour value in the range between 0 and 23, which is zero-based.
       
  2773      *
       
  2774      * @param field the time field.
       
  2775      * @param up indicates if the value of the specified time field is to be
       
  2776      * rolled up or rolled down. Use true if rolling up, false otherwise.
       
  2777      * @see Calendar#add(int,int)
       
  2778      * @see Calendar#set(int,int)
       
  2779      */
       
  2780     abstract public void roll(int field, boolean up);
       
  2781 
       
  2782     /**
       
  2783      * Adds the specified (signed) amount to the specified calendar field
       
  2784      * without changing larger fields.  A negative amount means to roll
       
  2785      * down.
       
  2786      *
       
  2787      * <p>NOTE:  This default implementation on <code>Calendar</code> just repeatedly calls the
       
  2788      * version of {@link #roll(int,boolean) roll()} that rolls by one unit.  This may not
       
  2789      * always do the right thing.  For example, if the <code>DAY_OF_MONTH</code> field is 31,
       
  2790      * rolling through February will leave it set to 28.  The <code>GregorianCalendar</code>
       
  2791      * version of this function takes care of this problem.  Other subclasses
       
  2792      * should also provide overrides of this function that do the right thing.
       
  2793      *
       
  2794      * @param field the calendar field.
       
  2795      * @param amount the signed amount to add to the calendar <code>field</code>.
       
  2796      * @since 1.2
       
  2797      * @see #roll(int,boolean)
       
  2798      * @see #add(int,int)
       
  2799      * @see #set(int,int)
       
  2800      */
       
  2801     public void roll(int field, int amount)
       
  2802     {
       
  2803         while (amount > 0) {
       
  2804             roll(field, true);
       
  2805             amount--;
       
  2806         }
       
  2807         while (amount < 0) {
       
  2808             roll(field, false);
       
  2809             amount++;
       
  2810         }
       
  2811     }
       
  2812 
       
  2813     /**
       
  2814      * Sets the time zone with the given time zone value.
       
  2815      *
       
  2816      * @param value the given time zone.
       
  2817      */
       
  2818     public void setTimeZone(TimeZone value)
       
  2819     {
       
  2820         zone = value;
       
  2821         sharedZone = false;
       
  2822         /* Recompute the fields from the time using the new zone.  This also
       
  2823          * works if isTimeSet is false (after a call to set()).  In that case
       
  2824          * the time will be computed from the fields using the new zone, then
       
  2825          * the fields will get recomputed from that.  Consider the sequence of
       
  2826          * calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST).
       
  2827          * Is cal set to 1 o'clock EST or 1 o'clock PST?  Answer: PST.  More
       
  2828          * generally, a call to setTimeZone() affects calls to set() BEFORE AND
       
  2829          * AFTER it up to the next call to complete().
       
  2830          */
       
  2831         areAllFieldsSet = areFieldsSet = false;
       
  2832     }
       
  2833 
       
  2834     /**
       
  2835      * Gets the time zone.
       
  2836      *
       
  2837      * @return the time zone object associated with this calendar.
       
  2838      */
       
  2839     public TimeZone getTimeZone()
       
  2840     {
       
  2841         // If the TimeZone object is shared by other Calendar instances, then
       
  2842         // create a clone.
       
  2843         if (sharedZone) {
       
  2844             zone = (TimeZone) zone.clone();
       
  2845             sharedZone = false;
       
  2846         }
       
  2847         return zone;
       
  2848     }
       
  2849 
       
  2850     /**
       
  2851      * Returns the time zone (without cloning).
       
  2852      */
       
  2853     TimeZone getZone() {
       
  2854         return zone;
       
  2855     }
       
  2856 
       
  2857     /**
       
  2858      * Sets the sharedZone flag to <code>shared</code>.
       
  2859      */
       
  2860     void setZoneShared(boolean shared) {
       
  2861         sharedZone = shared;
       
  2862     }
       
  2863 
       
  2864     /**
       
  2865      * Specifies whether or not date/time interpretation is to be lenient.  With
       
  2866      * lenient interpretation, a date such as "February 942, 1996" will be
       
  2867      * treated as being equivalent to the 941st day after February 1, 1996.
       
  2868      * With strict (non-lenient) interpretation, such dates will cause an exception to be
       
  2869      * thrown. The default is lenient.
       
  2870      *
       
  2871      * @param lenient <code>true</code> if the lenient mode is to be turned
       
  2872      * on; <code>false</code> if it is to be turned off.
       
  2873      * @see #isLenient()
       
  2874      * @see java.text.DateFormat#setLenient
       
  2875      */
       
  2876     public void setLenient(boolean lenient)
       
  2877     {
       
  2878         this.lenient = lenient;
       
  2879     }
       
  2880 
       
  2881     /**
       
  2882      * Tells whether date/time interpretation is to be lenient.
       
  2883      *
       
  2884      * @return <code>true</code> if the interpretation mode of this calendar is lenient;
       
  2885      * <code>false</code> otherwise.
       
  2886      * @see #setLenient(boolean)
       
  2887      */
       
  2888     public boolean isLenient()
       
  2889     {
       
  2890         return lenient;
       
  2891     }
       
  2892 
       
  2893     /**
       
  2894      * Sets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
       
  2895      * <code>MONDAY</code> in France.
       
  2896      *
       
  2897      * @param value the given first day of the week.
       
  2898      * @see #getFirstDayOfWeek()
       
  2899      * @see #getMinimalDaysInFirstWeek()
       
  2900      */
       
  2901     public void setFirstDayOfWeek(int value)
       
  2902     {
       
  2903         if (firstDayOfWeek == value) {
       
  2904             return;
       
  2905         }
       
  2906         firstDayOfWeek = value;
       
  2907         invalidateWeekFields();
       
  2908     }
       
  2909 
       
  2910     /**
       
  2911      * Gets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
       
  2912      * <code>MONDAY</code> in France.
       
  2913      *
       
  2914      * @return the first day of the week.
       
  2915      * @see #setFirstDayOfWeek(int)
       
  2916      * @see #getMinimalDaysInFirstWeek()
       
  2917      */
       
  2918     public int getFirstDayOfWeek()
       
  2919     {
       
  2920         return firstDayOfWeek;
       
  2921     }
       
  2922 
       
  2923     /**
       
  2924      * Sets what the minimal days required in the first week of the year are;
       
  2925      * For example, if the first week is defined as one that contains the first
       
  2926      * day of the first month of a year, call this method with value 1. If it
       
  2927      * must be a full week, use value 7.
       
  2928      *
       
  2929      * @param value the given minimal days required in the first week
       
  2930      * of the year.
       
  2931      * @see #getMinimalDaysInFirstWeek()
       
  2932      */
       
  2933     public void setMinimalDaysInFirstWeek(int value)
       
  2934     {
       
  2935         if (minimalDaysInFirstWeek == value) {
       
  2936             return;
       
  2937         }
       
  2938         minimalDaysInFirstWeek = value;
       
  2939         invalidateWeekFields();
       
  2940     }
       
  2941 
       
  2942     /**
       
  2943      * Gets what the minimal days required in the first week of the year are;
       
  2944      * e.g., if the first week is defined as one that contains the first day
       
  2945      * of the first month of a year, this method returns 1. If
       
  2946      * the minimal days required must be a full week, this method
       
  2947      * returns 7.
       
  2948      *
       
  2949      * @return the minimal days required in the first week of the year.
       
  2950      * @see #setMinimalDaysInFirstWeek(int)
       
  2951      */
       
  2952     public int getMinimalDaysInFirstWeek()
       
  2953     {
       
  2954         return minimalDaysInFirstWeek;
       
  2955     }
       
  2956 
       
  2957     /**
       
  2958      * Returns whether this {@code Calendar} supports week dates.
       
  2959      *
       
  2960      * <p>The default implementation of this method returns {@code false}.
       
  2961      *
       
  2962      * @return {@code true} if this {@code Calendar} supports week dates;
       
  2963      *         {@code false} otherwise.
       
  2964      * @see #getWeekYear()
       
  2965      * @see #setWeekDate(int,int,int)
       
  2966      * @see #getWeeksInWeekYear()
       
  2967      * @since 1.7
       
  2968      */
       
  2969     public boolean isWeekDateSupported() {
       
  2970         return false;
       
  2971     }
       
  2972 
       
  2973     /**
       
  2974      * Returns the week year represented by this {@code Calendar}. The
       
  2975      * week year is in sync with the week cycle. The {@linkplain
       
  2976      * #getFirstDayOfWeek() first day of the first week} is the first
       
  2977      * day of the week year.
       
  2978      *
       
  2979      * <p>The default implementation of this method throws an
       
  2980      * {@link UnsupportedOperationException}.
       
  2981      *
       
  2982      * @return the week year of this {@code Calendar}
       
  2983      * @exception UnsupportedOperationException
       
  2984      *            if any week year numbering isn't supported
       
  2985      *            in this {@code Calendar}.
       
  2986      * @see #isWeekDateSupported()
       
  2987      * @see #getFirstDayOfWeek()
       
  2988      * @see #getMinimalDaysInFirstWeek()
       
  2989      * @since 1.7
       
  2990      */
       
  2991     public int getWeekYear() {
       
  2992         throw new UnsupportedOperationException();
       
  2993     }
       
  2994 
       
  2995     /**
       
  2996      * Sets the date of this {@code Calendar} with the the given date
       
  2997      * specifiers - week year, week of year, and day of week.
       
  2998      *
       
  2999      * <p>Unlike the {@code set} method, all of the calendar fields
       
  3000      * and {@code time} values are calculated upon return.
       
  3001      *
       
  3002      * <p>If {@code weekOfYear} is out of the valid week-of-year range
       
  3003      * in {@code weekYear}, the {@code weekYear} and {@code
       
  3004      * weekOfYear} values are adjusted in lenient mode, or an {@code
       
  3005      * IllegalArgumentException} is thrown in non-lenient mode.
       
  3006      *
       
  3007      * <p>The default implementation of this method throws an
       
  3008      * {@code UnsupportedOperationException}.
       
  3009      *
       
  3010      * @param weekYear   the week year
       
  3011      * @param weekOfYear the week number based on {@code weekYear}
       
  3012      * @param dayOfWeek  the day of week value: one of the constants
       
  3013      *                   for the {@link #DAY_OF_WEEK} field: {@link
       
  3014      *                   #SUNDAY}, ..., {@link #SATURDAY}.
       
  3015      * @exception IllegalArgumentException
       
  3016      *            if any of the given date specifiers is invalid
       
  3017      *            or any of the calendar fields are inconsistent
       
  3018      *            with the given date specifiers in non-lenient mode
       
  3019      * @exception UnsupportedOperationException
       
  3020      *            if any week year numbering isn't supported in this
       
  3021      *            {@code Calendar}.
       
  3022      * @see #isWeekDateSupported()
       
  3023      * @see #getFirstDayOfWeek()
       
  3024      * @see #getMinimalDaysInFirstWeek()
       
  3025      * @since 1.7
       
  3026      */
       
  3027     public void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) {
       
  3028         throw new UnsupportedOperationException();
       
  3029     }
       
  3030 
       
  3031     /**
       
  3032      * Returns the number of weeks in the week year represented by this
       
  3033      * {@code Calendar}.
       
  3034      *
       
  3035      * <p>The default implementation of this method throws an
       
  3036      * {@code UnsupportedOperationException}.
       
  3037      *
       
  3038      * @return the number of weeks in the week year.
       
  3039      * @exception UnsupportedOperationException
       
  3040      *            if any week year numbering isn't supported in this
       
  3041      *            {@code Calendar}.
       
  3042      * @see #WEEK_OF_YEAR
       
  3043      * @see #isWeekDateSupported()
       
  3044      * @see #getWeekYear()
       
  3045      * @see #getActualMaximum(int)
       
  3046      * @since 1.7
       
  3047      */
       
  3048     public int getWeeksInWeekYear() {
       
  3049         throw new UnsupportedOperationException();
       
  3050     }
       
  3051 
       
  3052     /**
       
  3053      * Returns the minimum value for the given calendar field of this
       
  3054      * <code>Calendar</code> instance. The minimum value is defined as
       
  3055      * the smallest value returned by the {@link #get(int) get} method
       
  3056      * for any possible time value.  The minimum value depends on
       
  3057      * calendar system specific parameters of the instance.
       
  3058      *
       
  3059      * @param field the calendar field.
       
  3060      * @return the minimum value for the given calendar field.
       
  3061      * @see #getMaximum(int)
       
  3062      * @see #getGreatestMinimum(int)
       
  3063      * @see #getLeastMaximum(int)
       
  3064      * @see #getActualMinimum(int)
       
  3065      * @see #getActualMaximum(int)
       
  3066      */
       
  3067     abstract public int getMinimum(int field);
       
  3068 
       
  3069     /**
       
  3070      * Returns the maximum value for the given calendar field of this
       
  3071      * <code>Calendar</code> instance. The maximum value is defined as
       
  3072      * the largest value returned by the {@link #get(int) get} method
       
  3073      * for any possible time value. The maximum value depends on
       
  3074      * calendar system specific parameters of the instance.
       
  3075      *
       
  3076      * @param field the calendar field.
       
  3077      * @return the maximum value for the given calendar field.
       
  3078      * @see #getMinimum(int)
       
  3079      * @see #getGreatestMinimum(int)
       
  3080      * @see #getLeastMaximum(int)
       
  3081      * @see #getActualMinimum(int)
       
  3082      * @see #getActualMaximum(int)
       
  3083      */
       
  3084     abstract public int getMaximum(int field);
       
  3085 
       
  3086     /**
       
  3087      * Returns the highest minimum value for the given calendar field
       
  3088      * of this <code>Calendar</code> instance. The highest minimum
       
  3089      * value is defined as the largest value returned by {@link
       
  3090      * #getActualMinimum(int)} for any possible time value. The
       
  3091      * greatest minimum value depends on calendar system specific
       
  3092      * parameters of the instance.
       
  3093      *
       
  3094      * @param field the calendar field.
       
  3095      * @return the highest minimum value for the given calendar field.
       
  3096      * @see #getMinimum(int)
       
  3097      * @see #getMaximum(int)
       
  3098      * @see #getLeastMaximum(int)
       
  3099      * @see #getActualMinimum(int)
       
  3100      * @see #getActualMaximum(int)
       
  3101      */
       
  3102     abstract public int getGreatestMinimum(int field);
       
  3103 
       
  3104     /**
       
  3105      * Returns the lowest maximum value for the given calendar field
       
  3106      * of this <code>Calendar</code> instance. The lowest maximum
       
  3107      * value is defined as the smallest value returned by {@link
       
  3108      * #getActualMaximum(int)} for any possible time value. The least
       
  3109      * maximum value depends on calendar system specific parameters of
       
  3110      * the instance. For example, a <code>Calendar</code> for the
       
  3111      * Gregorian calendar system returns 28 for the
       
  3112      * <code>DAY_OF_MONTH</code> field, because the 28th is the last
       
  3113      * day of the shortest month of this calendar, February in a
       
  3114      * common year.
       
  3115      *
       
  3116      * @param field the calendar field.
       
  3117      * @return the lowest maximum value for the given calendar field.
       
  3118      * @see #getMinimum(int)
       
  3119      * @see #getMaximum(int)
       
  3120      * @see #getGreatestMinimum(int)
       
  3121      * @see #getActualMinimum(int)
       
  3122      * @see #getActualMaximum(int)
       
  3123      */
       
  3124     abstract public int getLeastMaximum(int field);
       
  3125 
       
  3126     /**
       
  3127      * Returns the minimum value that the specified calendar field
       
  3128      * could have, given the time value of this <code>Calendar</code>.
       
  3129      *
       
  3130      * <p>The default implementation of this method uses an iterative
       
  3131      * algorithm to determine the actual minimum value for the
       
  3132      * calendar field. Subclasses should, if possible, override this
       
  3133      * with a more efficient implementation - in many cases, they can
       
  3134      * simply return <code>getMinimum()</code>.
       
  3135      *
       
  3136      * @param field the calendar field
       
  3137      * @return the minimum of the given calendar field for the time
       
  3138      * value of this <code>Calendar</code>
       
  3139      * @see #getMinimum(int)
       
  3140      * @see #getMaximum(int)
       
  3141      * @see #getGreatestMinimum(int)
       
  3142      * @see #getLeastMaximum(int)
       
  3143      * @see #getActualMaximum(int)
       
  3144      * @since 1.2
       
  3145      */
       
  3146     public int getActualMinimum(int field) {
       
  3147         int fieldValue = getGreatestMinimum(field);
       
  3148         int endValue = getMinimum(field);
       
  3149 
       
  3150         // if we know that the minimum value is always the same, just return it
       
  3151         if (fieldValue == endValue) {
       
  3152             return fieldValue;
       
  3153         }
       
  3154 
       
  3155         // clone the calendar so we don't mess with the real one, and set it to
       
  3156         // accept anything for the field values
       
  3157         Calendar work = (Calendar)this.clone();
       
  3158         work.setLenient(true);
       
  3159 
       
  3160         // now try each value from getLeastMaximum() to getMaximum() one by one until
       
  3161         // we get a value that normalizes to another value.  The last value that
       
  3162         // normalizes to itself is the actual minimum for the current date
       
  3163         int result = fieldValue;
       
  3164 
       
  3165         do {
       
  3166             work.set(field, fieldValue);
       
  3167             if (work.get(field) != fieldValue) {
       
  3168                 break;
       
  3169             } else {
       
  3170                 result = fieldValue;
       
  3171                 fieldValue--;
       
  3172             }
       
  3173         } while (fieldValue >= endValue);
       
  3174 
       
  3175         return result;
       
  3176     }
       
  3177 
       
  3178     /**
       
  3179      * Returns the maximum value that the specified calendar field
       
  3180      * could have, given the time value of this
       
  3181      * <code>Calendar</code>. For example, the actual maximum value of
       
  3182      * the <code>MONTH</code> field is 12 in some years, and 13 in
       
  3183      * other years in the Hebrew calendar system.
       
  3184      *
       
  3185      * <p>The default implementation of this method uses an iterative
       
  3186      * algorithm to determine the actual maximum value for the
       
  3187      * calendar field. Subclasses should, if possible, override this
       
  3188      * with a more efficient implementation.
       
  3189      *
       
  3190      * @param field the calendar field
       
  3191      * @return the maximum of the given calendar field for the time
       
  3192      * value of this <code>Calendar</code>
       
  3193      * @see #getMinimum(int)
       
  3194      * @see #getMaximum(int)
       
  3195      * @see #getGreatestMinimum(int)
       
  3196      * @see #getLeastMaximum(int)
       
  3197      * @see #getActualMinimum(int)
       
  3198      * @since 1.2
       
  3199      */
       
  3200     public int getActualMaximum(int field) {
       
  3201         int fieldValue = getLeastMaximum(field);
       
  3202         int endValue = getMaximum(field);
       
  3203 
       
  3204         // if we know that the maximum value is always the same, just return it.
       
  3205         if (fieldValue == endValue) {
       
  3206             return fieldValue;
       
  3207         }
       
  3208 
       
  3209         // clone the calendar so we don't mess with the real one, and set it to
       
  3210         // accept anything for the field values.
       
  3211         Calendar work = (Calendar)this.clone();
       
  3212         work.setLenient(true);
       
  3213 
       
  3214         // if we're counting weeks, set the day of the week to Sunday.  We know the
       
  3215         // last week of a month or year will contain the first day of the week.
       
  3216         if (field == WEEK_OF_YEAR || field == WEEK_OF_MONTH) {
       
  3217             work.set(DAY_OF_WEEK, firstDayOfWeek);
       
  3218         }
       
  3219 
       
  3220         // now try each value from getLeastMaximum() to getMaximum() one by one until
       
  3221         // we get a value that normalizes to another value.  The last value that
       
  3222         // normalizes to itself is the actual maximum for the current date
       
  3223         int result = fieldValue;
       
  3224 
       
  3225         do {
       
  3226             work.set(field, fieldValue);
       
  3227             if (work.get(field) != fieldValue) {
       
  3228                 break;
       
  3229             } else {
       
  3230                 result = fieldValue;
       
  3231                 fieldValue++;
       
  3232             }
       
  3233         } while (fieldValue <= endValue);
       
  3234 
       
  3235         return result;
       
  3236     }
       
  3237 
       
  3238     /**
       
  3239      * Creates and returns a copy of this object.
       
  3240      *
       
  3241      * @return a copy of this object.
       
  3242      */
       
  3243     @Override
       
  3244     public Object clone()
       
  3245     {
       
  3246         try {
       
  3247             Calendar other = (Calendar) super.clone();
       
  3248 
       
  3249             other.fields = new int[FIELD_COUNT];
       
  3250             other.isSet = new boolean[FIELD_COUNT];
       
  3251             other.stamp = new int[FIELD_COUNT];
       
  3252             for (int i = 0; i < FIELD_COUNT; i++) {
       
  3253                 other.fields[i] = fields[i];
       
  3254                 other.stamp[i] = stamp[i];
       
  3255                 other.isSet[i] = isSet[i];
       
  3256             }
       
  3257             other.zone = (TimeZone) zone.clone();
       
  3258             return other;
       
  3259         }
       
  3260         catch (CloneNotSupportedException e) {
       
  3261             // this shouldn't happen, since we are Cloneable
       
  3262             throw new InternalError(e);
       
  3263         }
       
  3264     }
       
  3265 
       
  3266     private static final String[] FIELD_NAME = {
       
  3267         "ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH",
       
  3268         "DAY_OF_YEAR", "DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR",
       
  3269         "HOUR_OF_DAY", "MINUTE", "SECOND", "MILLISECOND", "ZONE_OFFSET",
       
  3270         "DST_OFFSET"
       
  3271     };
       
  3272 
       
  3273     /**
       
  3274      * Returns the name of the specified calendar field.
       
  3275      *
       
  3276      * @param field the calendar field
       
  3277      * @return the calendar field name
       
  3278      * @exception IndexOutOfBoundsException if <code>field</code> is negative,
       
  3279      * equal to or greater then <code>FIELD_COUNT</code>.
       
  3280      */
       
  3281     static String getFieldName(int field) {
       
  3282         return FIELD_NAME[field];
       
  3283     }
       
  3284 
       
  3285     /**
       
  3286      * Return a string representation of this calendar. This method
       
  3287      * is intended to be used only for debugging purposes, and the
       
  3288      * format of the returned string may vary between implementations.
       
  3289      * The returned string may be empty but may not be <code>null</code>.
       
  3290      *
       
  3291      * @return  a string representation of this calendar.
       
  3292      */
       
  3293     @Override
       
  3294     public String toString() {
       
  3295         // NOTE: BuddhistCalendar.toString() interprets the string
       
  3296         // produced by this method so that the Gregorian year number
       
  3297         // is substituted by its B.E. year value. It relies on
       
  3298         // "...,YEAR=<year>,..." or "...,YEAR=?,...".
       
  3299         StringBuilder buffer = new StringBuilder(800);
       
  3300         buffer.append(getClass().getName()).append('[');
       
  3301         appendValue(buffer, "time", isTimeSet, time);
       
  3302         buffer.append(",areFieldsSet=").append(areFieldsSet);
       
  3303         buffer.append(",areAllFieldsSet=").append(areAllFieldsSet);
       
  3304         buffer.append(",lenient=").append(lenient);
       
  3305         buffer.append(",zone=").append(zone);
       
  3306         appendValue(buffer, ",firstDayOfWeek", true, (long) firstDayOfWeek);
       
  3307         appendValue(buffer, ",minimalDaysInFirstWeek", true, (long) minimalDaysInFirstWeek);
       
  3308         for (int i = 0; i < FIELD_COUNT; ++i) {
       
  3309             buffer.append(',');
       
  3310             appendValue(buffer, FIELD_NAME[i], isSet(i), (long) fields[i]);
       
  3311         }
       
  3312         buffer.append(']');
       
  3313         return buffer.toString();
       
  3314     }
       
  3315 
       
  3316     // =======================privates===============================
       
  3317 
       
  3318     private static void appendValue(StringBuilder sb, String item, boolean valid, long value) {
       
  3319         sb.append(item).append('=');
       
  3320         if (valid) {
       
  3321             sb.append(value);
       
  3322         } else {
       
  3323             sb.append('?');
       
  3324         }
       
  3325     }
       
  3326 
       
  3327     /**
       
  3328      * Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent.
       
  3329      * They are used to figure out the week count for a specific date for
       
  3330      * a given locale. These must be set when a Calendar is constructed.
       
  3331      * @param desiredLocale the given locale.
       
  3332      */
       
  3333     private void setWeekCountData(Locale desiredLocale)
       
  3334     {
       
  3335         /* try to get the Locale data from the cache */
       
  3336         int[] data = cachedLocaleData.get(desiredLocale);
       
  3337         if (data == null) {  /* cache miss */
       
  3338             data = new int[2];
       
  3339             data[0] = CalendarDataUtility.retrieveFirstDayOfWeek(desiredLocale);
       
  3340             data[1] = CalendarDataUtility.retrieveMinimalDaysInFirstWeek(desiredLocale);
       
  3341             cachedLocaleData.putIfAbsent(desiredLocale, data);
       
  3342         }
       
  3343         firstDayOfWeek = data[0];
       
  3344         minimalDaysInFirstWeek = data[1];
       
  3345     }
       
  3346 
       
  3347     /**
       
  3348      * Recomputes the time and updates the status fields isTimeSet
       
  3349      * and areFieldsSet.  Callers should check isTimeSet and only
       
  3350      * call this method if isTimeSet is false.
       
  3351      */
       
  3352     private void updateTime() {
       
  3353         computeTime();
       
  3354         // The areFieldsSet and areAllFieldsSet values are no longer
       
  3355         // controlled here (as of 1.5).
       
  3356         isTimeSet = true;
       
  3357     }
       
  3358 
       
  3359     private int compareTo(long t) {
       
  3360         long thisTime = getMillisOf(this);
       
  3361         return (thisTime > t) ? 1 : (thisTime == t) ? 0 : -1;
       
  3362     }
       
  3363 
       
  3364     private static long getMillisOf(Calendar calendar) {
       
  3365         if (calendar.isTimeSet) {
       
  3366             return calendar.time;
       
  3367         }
       
  3368         Calendar cal = (Calendar) calendar.clone();
       
  3369         cal.setLenient(true);
       
  3370         return cal.getTimeInMillis();
       
  3371     }
       
  3372 
       
  3373     /**
       
  3374      * Adjusts the stamp[] values before nextStamp overflow. nextStamp
       
  3375      * is set to the next stamp value upon the return.
       
  3376      */
       
  3377     private void adjustStamp() {
       
  3378         int max = MINIMUM_USER_STAMP;
       
  3379         int newStamp = MINIMUM_USER_STAMP;
       
  3380 
       
  3381         for (;;) {
       
  3382             int min = Integer.MAX_VALUE;
       
  3383             for (int v : stamp) {
       
  3384                 if (v >= newStamp && min > v) {
       
  3385                     min = v;
       
  3386                 }
       
  3387                 if (max < v) {
       
  3388                     max = v;
       
  3389                 }
       
  3390             }
       
  3391             if (max != min && min == Integer.MAX_VALUE) {
       
  3392                 break;
       
  3393             }
       
  3394             for (int i = 0; i < stamp.length; i++) {
       
  3395                 if (stamp[i] == min) {
       
  3396                     stamp[i] = newStamp;
       
  3397                 }
       
  3398             }
       
  3399             newStamp++;
       
  3400             if (min == max) {
       
  3401                 break;
       
  3402             }
       
  3403         }
       
  3404         nextStamp = newStamp;
       
  3405     }
       
  3406 
       
  3407     /**
       
  3408      * Sets the WEEK_OF_MONTH and WEEK_OF_YEAR fields to new values with the
       
  3409      * new parameter value if they have been calculated internally.
       
  3410      */
       
  3411     private void invalidateWeekFields()
       
  3412     {
       
  3413         if (stamp[WEEK_OF_MONTH] != COMPUTED &&
       
  3414             stamp[WEEK_OF_YEAR] != COMPUTED) {
       
  3415             return;
       
  3416         }
       
  3417 
       
  3418         // We have to check the new values of these fields after changing
       
  3419         // firstDayOfWeek and/or minimalDaysInFirstWeek. If the field values
       
  3420         // have been changed, then set the new values. (4822110)
       
  3421         Calendar cal = (Calendar) clone();
       
  3422         cal.setLenient(true);
       
  3423         cal.clear(WEEK_OF_MONTH);
       
  3424         cal.clear(WEEK_OF_YEAR);
       
  3425 
       
  3426         if (stamp[WEEK_OF_MONTH] == COMPUTED) {
       
  3427             int weekOfMonth = cal.get(WEEK_OF_MONTH);
       
  3428             if (fields[WEEK_OF_MONTH] != weekOfMonth) {
       
  3429                 fields[WEEK_OF_MONTH] = weekOfMonth;
       
  3430             }
       
  3431         }
       
  3432 
       
  3433         if (stamp[WEEK_OF_YEAR] == COMPUTED) {
       
  3434             int weekOfYear = cal.get(WEEK_OF_YEAR);
       
  3435             if (fields[WEEK_OF_YEAR] != weekOfYear) {
       
  3436                 fields[WEEK_OF_YEAR] = weekOfYear;
       
  3437             }
       
  3438         }
       
  3439     }
       
  3440 
       
  3441     /**
       
  3442      * Save the state of this object to a stream (i.e., serialize it).
       
  3443      *
       
  3444      * Ideally, <code>Calendar</code> would only write out its state data and
       
  3445      * the current time, and not write any field data out, such as
       
  3446      * <code>fields[]</code>, <code>isTimeSet</code>, <code>areFieldsSet</code>,
       
  3447      * and <code>isSet[]</code>.  <code>nextStamp</code> also should not be part
       
  3448      * of the persistent state. Unfortunately, this didn't happen before JDK 1.1
       
  3449      * shipped. To be compatible with JDK 1.1, we will always have to write out
       
  3450      * the field values and state flags.  However, <code>nextStamp</code> can be
       
  3451      * removed from the serialization stream; this will probably happen in the
       
  3452      * near future.
       
  3453      */
       
  3454     private synchronized void writeObject(ObjectOutputStream stream)
       
  3455          throws IOException
       
  3456     {
       
  3457         // Try to compute the time correctly, for the future (stream
       
  3458         // version 2) in which we don't write out fields[] or isSet[].
       
  3459         if (!isTimeSet) {
       
  3460             try {
       
  3461                 updateTime();
       
  3462             }
       
  3463             catch (IllegalArgumentException e) {}
       
  3464         }
       
  3465 
       
  3466         // If this Calendar has a ZoneInfo, save it and set a
       
  3467         // SimpleTimeZone equivalent (as a single DST schedule) for
       
  3468         // backward compatibility.
       
  3469         TimeZone savedZone = null;
       
  3470         if (zone instanceof ZoneInfo) {
       
  3471             SimpleTimeZone stz = ((ZoneInfo)zone).getLastRuleInstance();
       
  3472             if (stz == null) {
       
  3473                 stz = new SimpleTimeZone(zone.getRawOffset(), zone.getID());
       
  3474             }
       
  3475             savedZone = zone;
       
  3476             zone = stz;
       
  3477         }
       
  3478 
       
  3479         // Write out the 1.1 FCS object.
       
  3480         stream.defaultWriteObject();
       
  3481 
       
  3482         // Write out the ZoneInfo object
       
  3483         // 4802409: we write out even if it is null, a temporary workaround
       
  3484         // the real fix for bug 4844924 in corba-iiop
       
  3485         stream.writeObject(savedZone);
       
  3486         if (savedZone != null) {
       
  3487             zone = savedZone;
       
  3488         }
       
  3489     }
       
  3490 
       
  3491     private static class CalendarAccessControlContext {
       
  3492         private static final AccessControlContext INSTANCE;
       
  3493         static {
       
  3494             RuntimePermission perm = new RuntimePermission("accessClassInPackage.sun.util.calendar");
       
  3495             PermissionCollection perms = perm.newPermissionCollection();
       
  3496             perms.add(perm);
       
  3497             INSTANCE = new AccessControlContext(new ProtectionDomain[] {
       
  3498                                                     new ProtectionDomain(null, perms)
       
  3499                                                 });
       
  3500         }
       
  3501         private CalendarAccessControlContext() {
       
  3502         }
       
  3503     }
       
  3504 
       
  3505     /**
       
  3506      * Reconstitutes this object from a stream (i.e., deserialize it).
       
  3507      */
       
  3508     private void readObject(ObjectInputStream stream)
       
  3509          throws IOException, ClassNotFoundException
       
  3510     {
       
  3511         final ObjectInputStream input = stream;
       
  3512         input.defaultReadObject();
       
  3513 
       
  3514         stamp = new int[FIELD_COUNT];
       
  3515 
       
  3516         // Starting with version 2 (not implemented yet), we expect that
       
  3517         // fields[], isSet[], isTimeSet, and areFieldsSet may not be
       
  3518         // streamed out anymore.  We expect 'time' to be correct.
       
  3519         if (serialVersionOnStream >= 2)
       
  3520         {
       
  3521             isTimeSet = true;
       
  3522             if (fields == null) {
       
  3523                 fields = new int[FIELD_COUNT];
       
  3524             }
       
  3525             if (isSet == null) {
       
  3526                 isSet = new boolean[FIELD_COUNT];
       
  3527             }
       
  3528         }
       
  3529         else if (serialVersionOnStream >= 0)
       
  3530         {
       
  3531             for (int i=0; i<FIELD_COUNT; ++i) {
       
  3532                 stamp[i] = isSet[i] ? COMPUTED : UNSET;
       
  3533             }
       
  3534         }
       
  3535 
       
  3536         serialVersionOnStream = currentSerialVersion;
       
  3537 
       
  3538         // If there's a ZoneInfo object, use it for zone.
       
  3539         ZoneInfo zi = null;
       
  3540         try {
       
  3541             zi = AccessController.doPrivileged(
       
  3542                     new PrivilegedExceptionAction<ZoneInfo>() {
       
  3543                         @Override
       
  3544                         public ZoneInfo run() throws Exception {
       
  3545                             return (ZoneInfo) input.readObject();
       
  3546                         }
       
  3547                     },
       
  3548                     CalendarAccessControlContext.INSTANCE);
       
  3549         } catch (PrivilegedActionException pae) {
       
  3550             Exception e = pae.getException();
       
  3551             if (!(e instanceof OptionalDataException)) {
       
  3552                 if (e instanceof RuntimeException) {
       
  3553                     throw (RuntimeException) e;
       
  3554                 } else if (e instanceof IOException) {
       
  3555                     throw (IOException) e;
       
  3556                 } else if (e instanceof ClassNotFoundException) {
       
  3557                     throw (ClassNotFoundException) e;
       
  3558                 }
       
  3559                 throw new RuntimeException(e);
       
  3560             }
       
  3561         }
       
  3562         if (zi != null) {
       
  3563             zone = zi;
       
  3564         }
       
  3565 
       
  3566         // If the deserialized object has a SimpleTimeZone, try to
       
  3567         // replace it with a ZoneInfo equivalent (as of 1.4) in order
       
  3568         // to be compatible with the SimpleTimeZone-based
       
  3569         // implementation as much as possible.
       
  3570         if (zone instanceof SimpleTimeZone) {
       
  3571             String id = zone.getID();
       
  3572             TimeZone tz = TimeZone.getTimeZone(id);
       
  3573             if (tz != null && tz.hasSameRules(zone) && tz.getID().equals(id)) {
       
  3574                 zone = tz;
       
  3575             }
       
  3576         }
       
  3577     }
       
  3578 
       
  3579     /**
       
  3580      * Converts this object to an {@link Instant}.
       
  3581      * <p>
       
  3582      * The conversion creates an {@code Instant} that represents the
       
  3583      * same point on the time-line as this {@code Calendar}.
       
  3584      *
       
  3585      * @return the instant representing the same point on the time-line
       
  3586      * @since 1.8
       
  3587      */
       
  3588     public final Instant toInstant() {
       
  3589         return Instant.ofEpochMilli(getTimeInMillis());
       
  3590     }
       
  3591 }