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